I am working with 3 arrays (or potentially more or less) and my goal is to eliminate any common elements shared between them. For instance, in the first two arrays, the common elements are x
and z
, between the second and third array it's only t
, and between the first and third array, it's just k
. Essentially, I want to get rid of any duplicate elements that appear in multiple arrays.
!! Please note that the first array may also have common elements with the third one !!
This is what I have attempted so far, but it seems to be faltering:
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)
The expected outcome should look like this:
[
{
"id": "a",
"elems": [
"y"
]
},
{
"id": "b",
"elems": [
"u",
"i"
]
},
{
"id": "c",
"elems": [
"m",
"n",
"o"
]
}
]
What would be a correct and efficient solution for this? I have also tried combining all 3 arrays and removing duplicates, but then I struggle with splitting them back into separate arrays.. Any suggestions are welcome!