javascript - 删除多个数组之间的公共元素
问题描述
我有 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 个数组。谢谢!
解决方案
我会首先遍历所有元素并计算已经看到的次数。之后,我会再次循环并过滤掉不止一次看到的任何东西。
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)
推荐阅读
- python - 如何将 AzureML 笔记本文件夹中的文件夹下载到本地或 Blob 存储?
- flutter - 谷歌驱动器作为颤振应用程序的数据库(存储所有用户的文档)
- sql - PostgreSQL - 如何查找两个日期之间的差异大于 1 天/月的记录?
- php - 在也使用 php(php 日历)的 html 代码中,href 链接指向哪里?
- latex - 乳胶中破折号和不等式之间的空间
- asp.net - 创建允许两种 Web 应用程序访问方式的登录检查
- python - Python中列表反转的奇怪表现
- html - 如何在父级的 100% 高度填充图像并保存比例(宽度:图像高度)?
- mysql - 每个增量的运行总计
- python - 如何使用 Python LDAP3 列出自己的 Active Directory 组成员身份?