js实现分组
实现数组分组的方法
在JavaScript中,可以通过多种方式实现数组分组操作。以下是几种常见的实现方法:
使用reduce方法分组
const groupBy = (array, key) => {
return array.reduce((result, currentItem) => {
const groupKey = currentItem[key];
if (!result[groupKey]) {
result[groupKey] = [];
}
result[groupKey].push(currentItem);
return result;
}, {});
};
使用Object.groupBy方法(ES2023新增)

const grouped = Object.groupBy(items, ({ age }) => {
return age > 18 ? 'adult' : 'minor';
});
按条件分组
const groupByCondition = (array, callback) => {
return array.reduce((acc, item) => {
const key = callback(item);
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {});
};
分组后转换为数组
如果需要将分组结果转换为数组形式:

const groupToArray = (array, key) => {
const groups = {};
array.forEach(item => {
const groupKey = item[key];
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(item);
});
return Object.keys(groups).map(key => ({
key,
items: groups[key]
}));
};
多条件分组
实现基于多个属性的分组:
const multiGroupBy = (array, keys) => {
return array.reduce((result, item) => {
const groupKey = keys.map(k => item[k]).join('|');
if (!result[groupKey]) {
result[groupKey] = [];
}
result[groupKey].push(item);
return result;
}, {});
};
分组性能优化
对于大型数据集,可以考虑使用Map代替普通对象:
const groupByWithMap = (array, key) => {
const map = new Map();
array.forEach(item => {
const groupKey = item[key];
if (!map.has(groupKey)) {
map.set(groupKey, []);
}
map.get(groupKey).push(item);
});
return Object.fromEntries(map);
};
这些方法可以根据实际需求选择使用,reduce方法兼容性最好,而Object.groupBy是最新的标准方法但需要较新的JavaScript环境支持。






