首页 > 解决方案 > 删除多个数组之间的公共元素

问题描述

我有 3 个数组(或更多/更少,不是必须为 3,我只是举了一个例子),我想删除它们之间的所有公共元素。例如,在第一个 2 之间,公共元素是x and z,在第二个和第三个数组之间,公共元素是t。在第一个和第三个之间,共同的元素是k。基本上我想删除在多个数组中出现超过 1 次的任何元素。

!!第一个数组可以与第三个数组有共同的元素!

这是我到目前为止尝试过的,但它无法正常工作。

let y = [{
    id: 'a',
    elems: ['x', 'y', 'z', 'k']
  },
  {
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
  },
  {
    id: 'c',
    elems: ['m', 'n', 'k', 'o', 't']
  },
]

// x, z, t

for (let i = 0; i < y.length - 1; i++) {
  let current = y[i].elems
  let current2 = y[i + 1].elems

  if (current[i] == current2[i]) {
    const index = current.indexOf(current[i]);
    if (index > -1) {
      current.splice(index, 1);
      current2.splice(index, 1);
    }
  }
}

console.log(y)

期望的结果是

[
  {

    "id": "a",
    "elems": [
      "y"
    ]
  },
  {
    "id": "b",
    "elems": [
      "u",
      "i"
    ]
  },
  {
    "id": "c",
    "elems": [
      "m",
      "n",
      "o"
    ]
  }
]

这将是一个正确和最佳的解决方案?我还尝试连接 3 个数组并删除重复项,但是我不知道如何重新创建 3 个数组。谢谢!

标签: javascriptarraysduplicates

解决方案


我会首先遍历所有元素并计算已经看到的次数。之后,我会再次循环并过滤掉不止一次看到的任何东西。

const myData = [{
    id: 'a',
    elems: ['x', 'y', 'z']
  },
  {
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
  },
  {
    id: 'c',
    elems: ['m', 'n', 'o', 't']
  },
]

// count up every elem so we know which ones are duplicated
const allElems = myData.reduce((acc, item) => {
  item.elems.forEach( key => { 
    acc[key] = acc[key] || 0;
    acc[key]++;
  });
  return acc;
}, {})

// loop over all the elems and select only the elems that we have seen once
myData.forEach(item => {
  item.elems = item.elems.filter(key => allElems[key] === 1);
})

console.log(myData)


推荐阅读