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

JavaScript数组格式化:按make键分组生成子数组

JavaScript数组按品牌分组实现方案

需求说明

给定原始车辆数组:

var cars = [
  { make: 'audi', model: 'r8', year: '2012' },
  { make: 'audi', model: 'rs5', year: '2013' },
  { make: 'ford', model: 'mustang', year: '2012' },
  { make: 'ford', model: 'fusion', year: '2015' },
  { make: 'kia', model: 'optima', year: '2012' },
];

需要转换为按make字段分组的新结构:

var newCarsArr = [
  {
    make: 'audi',
    selected: [
      { make: 'audi', model: 'r8', year: '2012' },
      { make: 'audi', model: 'rs5', year: '2013' },
    ],
  },
  {
    make: 'ford',
    selected: [
      { make: 'ford', model: 'mustang', year: '2012' },
      { make: 'ford', model: 'fusion', year: '2015' },
    ],
  },
  {
    make: 'kia',
    selected: [{ make: 'kia', model: 'optima', year: '2012' }],
  },
];

实现方法一:用Array.reduce()快速分组

通过reduce遍历数组构建分组对象,再转成目标数组:

const newCarsArr = Object.values(
  cars.reduce((grouped, car) => {
    // 初始化当前品牌的分组结构
    if (!grouped[car.make]) {
      grouped[car.make] = { make: car.make, selected: [] };
    }
    // 将车辆添加到对应分组
    grouped[car.make].selected.push(car);
    return grouped;
  }, {})
);

console.log(newCarsArr);

实现方法二:用Map对象清晰分组

Map处理键值对分组逻辑更直观:

const carGroupMap = new Map();

cars.forEach(car => {
  const brand = car.make;
  if (!carGroupMap.has(brand)) {
    carGroupMap.set(brand, { make: brand, selected: [] });
  }
  carGroupMap.get(brand).selected.push(car);
});

// 把Map的值转为数组
const newCarsArr = Array.from(carGroupMap.values());

console.log(newCarsArr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:25:22