📜  Lodash _.groupBy() 方法

📅  最后修改于: 2022-05-13 01:56:22.548000             🧑  作者: Mango

Lodash _.groupBy() 方法

Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、集合、字符串、对象、数字等。

_.groupBy() 方法创建一个由通过 iteratee函数运行集合的每个元素的结果生成的键组成的对象。分组值的顺序由它们在集合中出现的顺序决定。此外,每个键的对应值是负责生成键的元素数组。

句法:

_.groupBy( collection, iteratee )

参数:此方法接受上面提到的两个参数,如下所述:

  • 集合:它是方法迭代的集合。
  • iteratee:它是为数组中的每个元素调用的函数。

返回值:此方法返回组合的聚合对象。

示例 1:

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = ([6.5, 4.12, 6.8, 5.4]);
  
// Using the _.groupBy() method
let grouped_data = _.groupBy(users, Math.floor )
  
console.log(grouped_data);

输出:

{ '4': [ 4.12 ], '5': [ 5.4 ], '6':[ 6.5, 6.8 ] }

示例 2:

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = (['eight', 'nine', 'four', 'seven']);
   
// Using of _.groupBy() method
// with the `_.property` iteratee shorthand 
let grouped_data = _.groupBy(users, 'length')
  
console.log(grouped_data);

输出:

{ '4': [ 'nine', 'four' ], '5': [ 'eight', 'seven' ]}

示例 3:

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var users = (['one', 'two', 'three', 'four']);
var obj = ([ 3.1, 1.2, 3.3 ]);
   
// Using the _.groupBy() method
// with the `_.property` iteratee shorthand 
let grouped_data = _.groupBy(users, 'length')
let grouped_data2 = _.groupBy(obj, Math.floor)
  
// Printing the output 
console.log(grouped_data, grouped_data2);

输出:

{ '3': [ 'one', 'two' ], '4': [ 'four' ], '5': [ 'three' ] } 
{ '1': [ 1.2 ], '3': [ 3.1, 3.3 ] }