JavaScript对象数组reduce分组:按value聚合index生成索引键对象
问题描述
我有一个对象数组,需要将其转换为以连续数字为键的对象,键对应的值是按原数组元素的value字段聚合的index数组。
我的代码
const data = [ { index: 1, value: "111" }, { index: 2, value: "121" }, { index: 3, value: "111" }, { index: 5, value: "111" }, { index: 6, value: "121" }, { index: 7, value: "121" }, ]; const getGroupBy = (data) => { return data.reduce((acc, curr, currIndex, arr) => { const val = curr.value; const idx = curr.index; const fValues = arr.filter((el) => el.value === val).map(el => el.index); if (acc.hasOwnProperty(currIndex)) { acc[currIndex] = arr.filter((el) => el.value === val); } else { Object.assign(acc, { [0]: [idx] }); } return acc; }, {}); }; console.log(getGroupBy(data));
期望输出
{ 0: [1,3,5], 1: [2,6,7] }
修正后的实现
你的原始代码逻辑存在重复遍历、分组映射错误的问题,下面是更高效且符合需求的实现:
const data = [ { index: 1, value: "111" }, { index: 2, value: "121" }, { index: 3, value: "111" }, { index: 5, value: "111" }, { index: 6, value: "121" }, { index: 7, value: "121" }, ]; const getGroupBy = (data) => { // 第一步:按value字段聚合对应的index数组 const valueMap = data.reduce((acc, item) => { acc[item.value] = acc[item.value] || []; acc[item.value].push(item.index); return acc; }, {}); // 第二步:将聚合结果转为连续数字键的对象 return Object.values(valueMap).reduce((acc, group, idx) => { acc[idx] = group; return acc; }, {}); }; console.log(getGroupBy(data));
逻辑说明
- 第一次
reduce只遍历数组一次,把相同value对应的index收集到同一数组中,避免了重复过滤的性能浪费 - 第二次
reduce把聚合后的数组列表,转换为以0开始的连续数字为键的对象,完全匹配期望输出
内容的提问来源于stack exchange,提问作者forest smoker
相关产品推荐
相关产品推荐

