删除两个数组javascript之间的非常见项

dia*_*old 2 javascript arrays

我有一个函数来删除javascript中两个数组之间的非常见元素,但问题是我的代码减少了数组中的一些项目并增加了一些.以下是我的代码

function canFormPairs(cleanSocks, dirtySocks) {
  let compared = [];
  cleanSocks.forEach(item => {
    dirtySocks.forEach(dItem => {
      if (item == dItem) {
        compared.push(item);
      }
    });
  });
  return compared;
}
console.log(canFormPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了

[ 1, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 5, 5 ]
Run Code Online (Sandbox Code Playgroud)

而不是期望的结果

[1, 1, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7]
Run Code Online (Sandbox Code Playgroud)

排序时

请问这段代码有什么问题

Cer*_*nce 7

您当前的逻辑会为两个数组之间的每个唯一索引匹配推送项目.例如,7,7在索引3(第一个数组)和索引3(第二个数组)匹配,因此它被推送一次.然后,下一个匹配是索引3(第一个数组)和索引7(第二个数组).没有更多的索引匹配比其他3-33-7,所以只有两个7(值)获得推.

我考虑Set从两个数组中创建一个,然后组合两个数组并使用它.filter来删除不在两个数组中的元素,然后对数组进行排序:

function canFormPairs(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  return [...a, ...b]
    .filter(item => setA.has(item) && setB.has(item))
    .sort((a, b) => a - b);
}
console.log(canFormPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));
Run Code Online (Sandbox Code Playgroud)