Home > Mobile >  Remove multiple elements from nested arrays
Remove multiple elements from nested arrays

Time:12-10

Assume there is a nested array like this:

[
    [ 'one', 'third ],
    [ 'one', 'second', 'fourth' ],
    [ 'one', 'third' ],
]

I need to make the values unique by order priority: If an element is existing in the first array, it should be removed from the second and third. An element of the second array should not exist in the third.

So the result should be:

[
    [ 'one', 'third ],
    [ 'second', 'fourth' ],
    [],
]

I would iterate over each array and each element, but this removes an element only from the next array (which is missing the last array or errors if the loop is at the last array) and it feels very hacky...

for (let i = 0; i < array.length; i  ) {
    const element = array[i];
    for (let j = 0; j < element.length; j  ) {
        const string = element[j];
        const index = array[i   1].indexOf(string)
        if (index !== -1) {
            array[i   1].splice(index, 1)
        }
    }
}

CodePudding user response:

You could take a Set and filter the values with a lookup and adding the value, if not seen.

const
    values = new Set,
    data = [['one', 'third'], ['one', 'second', 'fourth'], ['one', 'third']],
    result = data.map(a => a.filter(v => !values.has(v) && values.add(v)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

It can also be using immutable programming using reduce() and flat()

const data = [[ 'one', 'third' ], [ 'one', 'second', 'fourth' ],[ 'one', 'third' ]];
const result = data.reduce((acc, val) => [
     ...acc,
     val.filter(item => !acc.flat().includes(item))
], []);

console.log(result);

CodePudding user response:

It doesn't get much simpler than what you have done. Here is an alternative approach using a nested .forEach() and a hash u to keep track of already encountered array elements:

const arr=[
[ 'one', 'third' ],
[ 'one', 'second', 'fourth' ],
[ 'one', 'third' ],
];

const res=[], u={};
arr.forEach(r=>{
  res.push([]);
  r.forEach((c,i)=>{
   u[c] || (u[c]=res[res.length-1].push(c))
})});

console.log(res);

  • Related