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

嵌套循环按类别排序数组问题:未归至Other及重复添加异常

问题解决与实现方案

一、数组按type归类问题修复

错误原因分析

  1. 重复添加问题:嵌套for of循环未做精准匹配判断,每个元素遍历所有类别时都执行了添加操作,而非仅匹配对应类别时才添加。
  2. other类别未捕获milk/meat:缺少“未匹配到指定类别时归入other”的逻辑,仅处理了明确匹配的类别。

修复后的代码

const arr = [
  { name: 'cheese', type: 'dairy' },
  { name: 'yogurt', type: 'dairy' },
  { name: 'beef', type: 'meat' },
  { name: 'milk', type: 'milk' },
  { name: 'apple', type: 'fruit' }
];

const categories = [
  { type: 'dairy', items: [] },
  { type: 'fruit', items: [] },
  { type: 'other', items: [] }
];

// 创建类别映射,提升查找效率
const categoryMap = new Map();
categories.forEach(cat => categoryMap.set(cat.type, cat.items));

for (const item of arr) {
  // 优先匹配指定类别,未匹配则归入other
  if (categoryMap.has(item.type)) {
    categoryMap.get(item.type).push(item);
  } else {
    categoryMap.get('other').push(item);
  }
}

console.log(categories);

代码说明

  • 用Map存储类别与对应items数组的映射,避免重复遍历categories数组,提升效率。
  • 明确判断逻辑:匹配到指定type就加入对应数组,否则直接归入other,解决milk/meat的归属问题。
  • 每个元素仅处理一次,彻底避免重复添加。

二、高效多键值匹配实现

如果需要基于多个键(比如type+name)做匹配,可将多键拼接成唯一字符串作为Map的key:

// 示例:基于type和name的多键匹配
const items = [
  { name: 'cheese', type: 'dairy', price: 5 },
  { name: 'yogurt', type: 'dairy', price: 3 },
  { name: 'beef', type: 'meat', price: 10 }
];

const itemMap = new Map();
items.forEach(item => {
  // 拼接多键生成唯一标识
  const key = `${item.type}_${item.name}`;
  itemMap.set(key, item);
});

// 查找匹配项
const targetKey = 'dairy_cheese';
console.log(itemMap.get(targetKey)); // 输出{ name: 'cheese', type: 'dairy', price: 5 }

三、找出两个数组的差异并显示为无序列表

假设对比对象数组,基于多键判断差异:

const arr1 = [
  { name: 'cheese', type: 'dairy' },
  { name: 'yogurt', type: 'dairy' },
  { name: 'apple', type: 'fruit' }
];

const arr2 = [
  { name: 'yogurt', type: 'dairy' },
  { name: 'beef', type: 'meat' },
  { name: 'milk', type: 'milk' }
];

// 生成两个数组的键集合
const arr1Keys = new Set(arr1.map(item => `${item.type}_${item.name}`));
const arr2Keys = new Set(arr2.map(item => `${item.type}_${item.name}`));

// 筛选出各自独有的元素
const onlyInArr1 = arr1.filter(item => !arr2Keys.has(`${item.type}_${item.name}`));
const onlyInArr2 = arr2.filter(item => !arr1Keys.has(`${item.type}_${item.name}`));

// 渲染为无序列表
function renderDiffList() {
  let html = '<h3>数组差异</h3>';
  html += '<h4>仅在arr1中存在:</h4><ul>';
  onlyInArr1.forEach(item => html += `<li>${item.name} (${item.type})</li>`);
  html += '</ul>';
  
  html += '<h4>仅在arr2中存在:</h4><ul>';
  onlyInArr2.forEach(item => html += `<li>${item.name} (${item.type})</li>`);
  html += '</ul>';
  
  document.body.innerHTML = html;
}

renderDiffList();

效果说明

页面会输出两个无序列表,分别展示两个数组独有的元素,基于type+name的组合键判断唯一性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:30:45