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

如何统计对象数组中各键下唯一车辆名称的数量

问题描述

给定如下对象数组:

const vehicle = [
  {
    a: [
      {
        vehicle_name: "Toyota",
        color: "black"
      },
      {
        vehicle_name: "Toyota",
        color: "red"
      },
      {
        vehicle_name: "Ford",
        color: "yellow"
      },
      {
        vehicle_name: "Toyota",
        color: "white"
      }
    ]
  },
  {
    b: [
      {
        vehicle_name: "Honda",
        color: "black"
      },
      {
        vehicle_name: "Honda",
        color: "red"
      },
      {
        vehicle_name: "Ford",
        color: "yellow"
      },
      {
        vehicle_name: "Toyota",
        color: "white"
      }
    ]
  }
]

需求

获取每个键对应的车辆总数,注意:若vehicle_name重复,仅计为1次。

预期输出

const result = [
  {
    a: {
      count: 2
    }
  },
  {
    b: {
      count: 3
    }
  }
]

说明

  • 键a的计数为2:虽有4条车辆数据,但Toyota重复出现仅计1次,实际有效车型为Toyota、Ford两种。
  • 键b的计数为3:包含Honda、Ford、Toyota三种不同车型。

实现方案

通过遍历数组结合Set特性统计唯一车型数量,代码如下:

const getUniqueVehicleCount = (vehicles) => {
  return vehicles.map(item => {
    const [key, carList] = Object.entries(item)[0];
    // 提取所有车型名称并去重
    const uniqueNames = new Set(carList.map(car => car.vehicle_name));
    return {
      [key]: {
        count: uniqueNames.size
      }
    };
  });
};

const result = getUniqueVehicleCount(vehicle);
console.log(result);

代码说明

  1. 用map遍历输入数组中的每个对象;
  2. 用Object.entries取出每个对象的键和对应的车辆列表;
  3. 用map提取所有vehicle_name,再通过Set自动去重;
  4. Set.size即为去重后的车型数量,最后组装成预期的结果结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:30:49