如何在JavaScript数组的分组内为对象分配分组索引
为数组分组内的对象分配索引(按分组、id排序后计数)
要实现需求,核心是先按分组聚合元素,每个分组内按id排序后分配索引,最后将索引映射回目标元素。具体操作如下:
- 按
group字段对数组元素分组 - 对每个分组内的元素按
id字符串升序排序 - 为排序后的分组元素分配从0开始的递增索引,用映射表记录每个
id对应的索引值 - 遍历目标数组(可保持原顺序或指定顺序),为每个元素添加
groupIndex字段
代码实现
首先定义初始数据:
let data = [ { "id": "AB", "name": "Fred", "group": 1}, { "id": "BC", "name": "Jane", "group": 2 }, { "id": "CD", "name": "Mary", "group": 1 }, { "id": "DE", "name": "Bob", "group": 2 }, { "id": "EF", "name": "Chris", "group": 1 }, { "id": "FG", "name": "Steve", "group": 2 }, { "id": "GH", "name": "Jim", "group": 2 } ];
步骤1:构建分组与索引映射表
// 按group字段分组 const groupMap = {}; data.forEach(item => { if (!groupMap[item.group]) { groupMap[item.group] = []; } groupMap[item.group].push(item); }); // 为每个分组排序并生成id到groupIndex的映射 const idToIndex = {}; Object.values(groupMap).forEach(groupItems => { // 按id字符串升序排序 groupItems.sort((a, b) => a.id.localeCompare(b.id)); // 分配索引并存入映射表 groupItems.forEach((item, index) => { idToIndex[item.id] = index; }); });
步骤2:生成目标数组
如果需要保持原数组顺序:
const result = data.map(item => ({ ...item, groupIndex: idToIndex[item.id] })); console.log(result); // 输出: // [ // { id: 'AB', name: 'Fred', group: 1, groupIndex: 0 }, // { id: 'BC', name: 'Jane', group: 2, groupIndex: 0 }, // { id: 'CD', name: 'Mary', group: 1, groupIndex: 1 }, // { id: 'DE', name: 'Bob', group: 2, groupIndex: 1 }, // { id: 'EF', name: 'Chris', group: 1, groupIndex: 2 }, // { id: 'FG', name: 'Steve', group: 2, groupIndex: 2 }, // { id: 'GH', name: 'Jim', group: 2, groupIndex: 3 } // ]
如果要生成你指定顺序的最终数组:
const dataGrouped = [ { "id": "DE", "name": "Bob", "group": 2, "groupIndex": idToIndex["DE"] }, { "id": "EF", "name": "Chris", "group": 1, "groupIndex": idToIndex["EF"] }, { "id": "BC", "name": "Jane", "group": 2, "groupIndex": idToIndex["BC"] }, { "id": "FG", "name": "Steve", "group": 2, "groupIndex": idToIndex["FG"] }, { "id": "AB", "name": "Fred", "group": 1, "groupIndex": idToIndex["AB"] }, { "id": "CD", "name": "Mary", "group": 1, "groupIndex": idToIndex["CD"] }, { "id": "GH", "name": "Jim", "group": 2, "groupIndex": idToIndex["GH"] } ]; console.log(dataGrouped); // 输出与你给出的最终结果完全一致
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

