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

循环无法正确分离数组非匹配项?求JavaScript数组非匹配元素提取方案

数组非共同元素收集重复问题分析

我尝试将两个数组中彼此不匹配的元素push到新建的空数组notMutualFollowers中,但当前代码执行后返回了60个重复元素,请问我哪里出错了?注:我正在学习相关内容,若问题较为基础请见谅。

原代码:

const bobsFollowers = ['James', 'Caleb', 'Rita', 'Samantha'];
const tinasFollowers = ['Maurice', 'Caleb', 'Samantha'];
const mutualFollowers = [];
const notMutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(tinasFollowers[j]);
    }
    for (let x = 0; x < tinasFollowers.length && bobsFollowers.length; x++) {
      if (bobsFollowers[i] !== tinasFollowers[j] && tinasFollowers[j] !== bobsFollowers[i])
    notMutualFollowers.push(bobsFollowers[i], tinasFollowers[j]);
    } 
  }
}

console.log(mutualFollowers);
console.log(notMutualFollowers);

错误原因分析

  1. 多余的三层循环:最内层的x循环完全没有存在的必要,它会让每一对不匹配的元素重复执行3次push操作。同时循环条件x < tinasFollowers.length && bobsFollowers.length存在逻辑错误——bobsFollowers.length是数值4,在布尔判断中永远为真,所以x循环会完整执行3次,直接导致元素数量暴增。
  2. 冗余的判断条件:bobsFollowers[i] !== tinasFollowers[j] && tinasFollowers[j] !== bobsFollowers[i]这两个条件完全等价,重复判断没有任何实际作用。
  3. 错误的收集逻辑:原代码在每次i和j对应的元素不匹配时就执行push,但没有考虑到同一个元素会被多次比较(比如James会和tinasFollowers的三个元素逐一比较,每次不匹配都执行push,再加上x循环的三次重复,导致James被重复添加9次)。

按原代码逻辑计算:bobsFollowers有4个元素,tinasFollowers有3个元素,总共有4×3=12次外层循环。其中匹配的元素有2个(Caleb、Samantha),剩下10次都是不匹配的情况。每次不匹配时,x循环跑3次,每次push两个元素,最终10×3×2=60个重复元素,和你看到的结果一致。


修正后的代码

要正确收集非共同元素,我们只需要分别找出两个数组中独有的元素,再合并即可:

const bobsFollowers = ['James', 'Caleb', 'Rita', 'Samantha'];
const tinasFollowers = ['Maurice', 'Caleb', 'Samantha'];
const mutualFollowers = [];
const notMutualFollowers = [];

// 收集共同关注者
for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(bobsFollowers[i]);
      break; // 找到匹配就跳出内层循环,避免重复添加
    }
  }
}

// 收集bobs独有的关注者
for (const follower of bobsFollowers) {
  if (!tinasFollowers.includes(follower)) {
    notMutualFollowers.push(follower);
  }
}

// 收集tinas独有的关注者
for (const follower of tinasFollowers) {
  if (!bobsFollowers.includes(follower)) {
    notMutualFollowers.push(follower);
  }
}

console.log(mutualFollowers); // 输出: ["Caleb", "Samantha"]
console.log(notMutualFollowers); // 输出: ["James", "Rita", "Maurice"]

代码说明

  • 收集共同关注者时,找到匹配元素后用break跳出内层循环,避免同一个元素因多次比较被重复添加。
  • 收集非共同元素时,分别遍历两个数组,用includes()方法检查元素是否存在于对方数组中,不存在则添加到目标数组,确保每个元素只被添加一次。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:20:35