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

如何按name键分组对象数组并收集对应元素索引?

问题分析与解决

你的代码存在两个关键问题:

  • 索引获取错误:reduce的回调函数本身就提供了第三个参数index,这就是当前元素在数组中的位置,完全不需要用findIndex。而且findIndex(item)的用法是错误的——它需要传入判断条件的回调函数,直接传item会导致获取的索引完全不符合预期。
  • 返回格式不符:你的代码最终得到的是一个{name: 索引数组}的聚合对象,但预期结果是一个数组,每个元素是仅包含单个name键值对的对象。

修正后的代码

// 第一步:用reduce按name分组,得到{ bene: [0,2], leg: [1,3], hello: [4] }
const groupedObj = FinalArray.reduce((agg, item, index) => {
  const name = item.name || "";
  // 若当前name未在聚合对象中,初始化空数组
  if (!agg[name]) {
    agg[name] = [];
  }
  // 直接使用reduce自带的index参数
  agg[name].push(index);
  return agg;
}, {});

// 第二步:将分组对象转换为预期的数组格式
const result = Object.entries(groupedObj).map(([key, value]) => ({
  [key]: value
}));

console.log(result);

运行结果

[
  {bene: [0,2]},
  {leg: [1,3]},
  {hello: [4]}
]

简化写法

如果想一步完成逻辑,可以把对象转数组的操作整合进去,不过分开写更便于理解:

const result = Object.entries(
  FinalArray.reduce((agg, item, index) => {
    const name = item.name || "";
    agg[name] = [...(agg[name] || []), index];
    return agg;
  }, {})
).map(([k, v]) => ({[k]: v}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:27:35