如何对比两个数组对象的匹配数据,返回带餐厅计数的新数组
实现代码与思路
实现步骤
- 构建菜系计数映射表,给所有可选菜系预置初始计数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
相关产品推荐
相关产品推荐

