You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按属性对数组分组并将结果从0开始重新索引

解决方案:将分组结果转为从0开始索引的数组

嘿,你的groupItemBy函数已经完美实现了按指定属性(包括嵌套属性,比如'parent.child')分组的功能,不过它返回的是一个以属性值为键的对象。如果想要把分组结果改成从0开始重新索引的结构,其实只需要一步转换就搞定啦!

方法1:基于现有函数的结果转换

原函数返回的哈希对象,我们可以用Object.values()提取它的所有值,这些值就是各个分组的数组,提取后会自动形成一个从0开始索引的新数组:

// 示例数组
const sampleArray = [
  { type: 'fruit', name: 'apple' },
  { type: 'vegetable', name: 'carrot' },
  { type: 'fruit', name: 'banana' }
];

// 用你的函数分组
const groupedObj = groupItemBy(sampleArray, 'type');
// groupedObj 是 { fruit: [...], vegetable: [...] }

// 转为从0开始索引的数组
const indexedGroups = Object.values(groupedObj);
// indexedGroups 结果:[[{type:'fruit',...}, {type:'fruit',...}], [{type:'vegetable',...}]]

Object.values()会按照属性的插入顺序(现代浏览器均支持)返回对象的值数组,索引从0开始,完全符合你的需求。

方法2:修改原函数直接返回索引化结果

如果你想让函数直接返回目标格式,可以在原函数最后把哈希对象转为数组后返回:

groupItemBy(array, property) {
  let hash = {}, props = property.split('.');
  for (let i = 0; i < array.length; i++) {
    let key = props.reduce( (acc, prop) => {
      return acc && acc[prop];
    }, array[i]);
    if (!hash[key]) hash[key] = [];
    hash[key].push(array[i]);
  }
  // 新增:将哈希对象的值转为数组返回
  return Object.values(hash);
}

这样调用函数后,直接就能拿到从0开始索引的分组数组啦。

额外扩展:保留分组键的同时索引化

如果需要同时保留每个分组对应的属性值(比如知道某个分组是'fruit'还是'vegetable'),可以把分组包装成包含键和值的对象数组:

const indexedGroupsWithKeys = Object.entries(groupedObj).map(([key, items]) => ({
  groupKey: key,
  items: items
}));
// 结果:
// [
//   { groupKey: 'fruit', items: [...] },
//   { groupKey: 'vegetable', items: [...] }
// ]

这个结构既保留了分组的标识,又有从0开始的索引,使用起来更灵活~

内容的提问来源于stack exchange,提问作者ang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:24:01