js实现分组
实现数组分组的方法
在JavaScript中,可以通过多种方式实现数组分组操作。以下是几种常见的方法:
使用reduce方法
通过Array.prototype.reduce()方法可以高效地对数组进行分组:
const groupBy = (array, key) => {
return array.reduce((result, currentItem) => {
const groupKey = currentItem[key];
(result[groupKey] = result[groupKey] || []).push(currentItem);
return result;
}, {});
};
// 示例用法
const data = [
{ id: 1, category: 'A' },
{ id: 2, category: 'B' },
{ id: 3, category: 'A' }
];
const groupedData = groupBy(data, 'category');
使用forEach循环
通过简单的forEach循环也能实现分组:

function groupBy(array, property) {
const grouped = {};
array.forEach(item => {
const key = item[property];
if (!grouped[key]) {
grouped[key] = [];
}
grouped[key].push(item);
});
return grouped;
}
使用Map对象
利用Map对象可以创建更灵活的分组结构:
function groupByMap(array, keyFn) {
const map = new Map();
array.forEach(item => {
const key = keyFn(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return map;
}
// 示例用法
const result = groupByMap(data, item => item.category);
使用lodash库
如果项目中已经使用了lodash,可以直接使用其groupBy方法:

const _ = require('lodash');
const grouped = _.groupBy(data, 'category');
按条件分组
当需要根据更复杂的条件而非简单属性值进行分组时:
function groupByCondition(array, conditionFn) {
return array.reduce((acc, item) => {
const key = conditionFn(item);
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {});
}
// 示例:按字符串长度分组
const strings = ['a', 'bb', 'ccc', 'dd'];
const groupedByLength = groupByCondition(strings, str => str.length);
多级分组
对于需要多层嵌套的分组情况:
function multiLevelGroup(array, ...keys) {
return array.reduce((result, item) => {
keys.reduce((acc, key, i) => {
const groupKey = item[key];
if (i === keys.length - 1) {
(acc[groupKey] = acc[groupKey] || []).push(item);
} else {
acc[groupKey] = acc[groupKey] || {};
}
return acc[groupKey];
}, result);
return result;
}, {});
}
这些方法覆盖了从简单到复杂的分组需求,可以根据具体场景选择最适合的实现方式。






