如何用原生javascript实现groupBy?
[Definition of groupBy]创建一个由关键字组成的对象,这些关键字是通过迭代器运行集合的每个元素的结果生成的。分组值的顺序由它们在集合中出现的顺序确定。每个键的相应值是负责生成键的元素数组。使用一个参数调用iteratee:(value)。
[期望输出] groupBy([6.1, 4.2, 6.3], Math.floor); // => { '4': [4.2], '6': [6.1, 6.3] } groupBy(['one', 'two', 'three'], 'length'); // => { '3': ['one', 'two'], '5': ['three'] }
发布于 2018-03-19 14:42:00
您可以将Array.reduce()与对象一起使用来收集项。通过将迭代器应用于项来创建键。
iteratee可以是一个字符串,也可以是一个函数,所以我们需要检查类型,以及是否是从项中提取属性的字符串create函数。
集合可以是一个数组,也可以是一个对象,我们可以使用Object.values()来获取一个数组。
const groupBy = (collection, iteratee = (x) => x) => {
const it = typeof iteratee === 'function' ?
iteratee : ({ [iteratee]: prop }) => prop;
const array = Array.isArray(collection) ? collection : Object.values(collection);
return array.reduce((r, e) => {
const k = it(e);
r[k] = r[k] || [];
r[k].push(e);
return r;
}, {});
};
console.log(groupBy([6.1, 4.2, 6.3], Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }
console.log(groupBy(['one', 'two', 'three'], 'length')); // => { '3': ['one', 'two'], '5': ['three'] }
console.log(groupBy({ a: 6.1, b: 4.2, c: 6.3 }, Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }
发布于 2018-03-19 14:42:05
您可以使用reduce并公开一个generic group-by-key function。
function groupBy(arr, groupByKeyFn )
{
return arr.reduce( (acc, c) => {
var key = groupByKeyFn(c);
acc[key] = acc[key] || [];
acc[key].push(c)
return acc;
}, [])
}现在,您可以像这样使用此函数
var arr1 = [6.1, 4.2, 6.3];
var arr2 = ['one', 'two', 'three'];
console.log( groupBy(arr1, s => Math.floor(s) ) );
console.log( groupBy(arr2, s => s.length ) );演示
function groupBy(arr, groupByKeyFn) {
return arr.reduce((acc, c) => {
var key = groupByKeyFn(c);
acc[key] = acc[key] || [];
acc[key].push(c)
return acc;
}, {})
}
var arr1 = [6.1, 4.2, 6.3];
var arr2 = ['one', 'two', 'three'];
console.log( groupBy(arr1, s => Math.floor(s) ) );
console.log( groupBy(arr2, s => s.length ) );
https://stackoverflow.com/questions/49357039
复制相似问题