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

如何更简洁地从对象数组提取相似项并生成指定格式新数组?

更简洁的数组分组实现方案

你的需求是将对象数组按type字段分组,生成包含type和对应tests数组的新结构。现有代码逻辑可行但存在冗余(比如多次遍历dataNeeded),可以通过使用对象作为中间映射表来优化,大幅减少遍历次数,代码更简洁高效。

优化后的代码

const data = [
  { id: 1, type: 'easy', name: 'type 1', class: 12 },
  { id: 2, type: 'easy', name: 'type 2', class: 10 },
  { id: 3, type: 'medium', name: 'type 3', class: 12 },
  { id: 4, type: 'hard', name: 'type 4', class: 10 },
  { id: 5, type: 'medium', name: 'type 5', class: 10 },
  { id: 6, type: 'easy', name: 'type 2', class: 10 },
  { id: 7, type: 'medium', name: 'type 3', class: 12 },
  { id: 8, type: 'hard', name: 'type 4', class: 10 },
  { id: 9, type: 'medium', name: 'type 5', class: 10 },
  { id: 10, type: 'hard', name: 'type 4', class: 10 },
];

// 使用对象做映射,key为type值,value为对应的分组对象
const groupMap = {};

data.forEach(item => {
  if (!groupMap[item.type]) {
    groupMap[item.type] = { type: item.type, tests: [] };
  }
  groupMap[item.type].tests.push(item);
});

// 将映射表的值转为数组,得到最终结果
const dataNeeded = Object.values(groupMap);

console.log(dataNeeded);

优化点说明

  • 降低时间复杂度:原代码每次判断分组是否存在时,需调用find和二次遍历dataNeeded,时间复杂度为O(n²);优化后仅遍历原数组一次,映射表访问为O(1),时间复杂度降至O(n)。
  • 简化逻辑结构:用groupMap存储已有的分组,通过type键快速定位,避免嵌套条件判断和重复代码。
  • 提升可读性:核心逻辑一目了然,无需冗余的长度判断和重复的push操作。

函数式风格写法(使用Array.reduce)

如果偏好函数式编程风格,可以用reduce一步完成分组:

const dataNeeded = data.reduce((acc, item) => {
  const group = acc.find(g => g.type === item.type);
  group ? group.tests.push(item) : acc.push({ type: item.type, tests: [item] });
  return acc;
}, []);

注意:这种写法的时间复杂度仍为O(n²),数据量较大时推荐使用映射表方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:10:37