You need to enable JavaScript to run this app. 如何对比两个数组对象的匹配数据,返回带餐厅计数的新数组
优惠活动
大模型
产品
解决方案
定价
更多

如何对比两个数组对象的匹配数据,返回带餐厅计数的新数组

实现代码与思路

实现步骤

  • 构建菜系计数映射表,给所有可选菜系预置初始计数0,避免后续重复遍历餐厅列表造成的性能损耗
  • 遍历所有餐厅条目,将每个餐厅覆盖的菜系对应计数累加,仅统计在可选菜系列表内的名称,自动过滤无效脏数据
  • 遍历原始菜系列表,从计数映射表中取出对应数值,组装为符合要求的新数组

完整可运行代码

const restaurant = [
    { name: 'La mesa', cuisine: ['chiness', 'arabic'] },
    { name: 'Purnima', cuisine: ['thai'] },
    { name: 'Red Bull', cuisine: ['french', 'arabic'] },
    { name: 'Pasta', cuisine: ['indian'] },
];

const cuisine = [
    { name: 'chiness' },
    { name: 'arabic' },
    { name: 'thai' },
    { name: 'french' },
    { name: 'italian' },
    { name: 'indian' },
    { name: 'mexican' },
];

// 初始化菜系计数映射,默认每个菜系计数为0
const cuisineCounter = cuisine.reduce((counter, cuisineItem) => {
  counter[cuisineItem.name] = 0;
  return counter;
}, {});

// 遍历所有餐厅,累加对应菜系的关联餐厅数
restaurant.forEach(restItem => {
  restItem.cuisine.forEach(cuisineName => {
    // 仅统计可选列表内的菜系,避免无效数据干扰计数
    if (cuisineCounter.hasOwnProperty(cuisineName)) {
      cuisineCounter[cuisineName] += 1;
    }
  });
});

// 生成最终结果数组
const myCuisine = cuisine.map(cuisineItem => ({
  name: cuisineItem.name,
  restaurant: cuisineCounter[cuisineItem.name]
}));

运行上述代码得到的myCuisine数组和预期输出完全一致,未匹配到关联餐厅的菜系会自动赋值为0,存在匹配的菜系会准确统计关联的餐厅数量。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 09:24:03