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

如何按index和name分组数组并合并对应price数组?

数组合并解决方案

需要处理的原始数组:

[
    {
        index: 4,
        name: "car",
        price: [10,20,30]
    },
    {
        index: 4,
        name: "car",
        price: [40,50,60]
    },
    {
        index: 3,
        name: "bike",
        price: [40,50,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [10,20,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [70]
    },
]

目标是合并所有index和name均相同的对象,将它们的price数组合并,得到如下结果:

[
    {
        index: 4,
        name: "car",
        price: [40,50,60,10,20,30]
    },
    {
        index: 3,
        name: "bike",
        price: [40,50,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [10,20,60,70]
    }
]

可以用JavaScript的reduce方法实现分组合并,代码如下:

const originalArray = [
    { index: 4, name: "car", price: [10,20,30] },
    { index: 4, name: "car", price: [40,50,60] },
    { index: 3, name: "bike", price: [40,50,60] },
    { index: 2, name: "scooter", price: [10,20,60] },
    { index: 2, name: "scooter", price: [70] },
];

const mergedArray = Object.values(originalArray.reduce((acc, current) => {
    // 用index和name组合成唯一标识键
    const key = `${current.index}-${current.name}`;
    if (!acc[key]) {
        // 首次遇到该分组,存入对象副本
        acc[key] = { ...current };
    } else {
        // 合并price数组,按示例中car的顺序,后出现的数组在前拼接
        acc[key].price = current.price.concat(acc[key].price);
        // 若需按遍历顺序追加后续数组,替换为:acc[key].price = acc[key].price.concat(current.price)
    }
    return acc;
}, {}));

console.log(mergedArray);

代码说明

  • 借助reduce遍历数组,用index-name作为唯一键来分组对象
  • 首次遇到分组时,存入当前对象的副本(避免修改原数组对象)
  • 重复遇到分组时,合并price数组,可根据需求调整拼接顺序
  • 最后通过Object.values()将分组对象转为最终数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:52:15