数组分组,将传入的数据按指定特征进行分组
输入:数组值,函数或属性
输出:对象 key:数组所有元素经过处理后的值 value:相同key的数组元素集合
let arrFloatingPointNumber = [7.7, 5.2, 7.3],
arrLength = ['one', 'two', 'weet', 'thren'];
function groupBy(arr, fn) {
return arr.map(item => {
if (typeof fn === 'function') {
return fn(item);
} else {
return item[fn];
}
}).reduce((pre, cur, i) => {
if (!pre[cur]) {
pre[cur] = [arr[i]];
} else {
pre[cur] = pre[cur].concat(arr[i]);
}
return pre;
}, {});
}
console.log('arrFloatingPointNumber:', groupBy(arrFloatingPointNumber, Math.floor));
// arrFloatingPointNumber: {5: Array(1), 7: Array(2)}
console.log('arrLength:', groupBy(arrLength, 'length'));
// arrLength: {3: Array(2), 4: Array(1), 5: Array(1)}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)