javascript: how to remove duplicate arrays inside array of arrays

Viewed 17365

Input:

[[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]]

The output I want:

[[-1,-1,2],[-1,0,1]]

Any other ideas except this one?

Thanks

6 Answers

Magic

d.filter(( t={}, a=> !(t[a]=a in t) ));

I assume your input data are in array d. Explanation here.

let d = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];

var r = d.filter((t={},a=>!(t[a]=a in t)));

console.log(JSON.stringify(r));

const removeDuplicates = (arr = []) => {
    const map = new Map();
    arr.forEach((x) => map.set(JSON.stringify(x), x));
    arr = [...map.values()];
    return arr;
};

console.log(
    removeDuplicates([
        [1, 1, 6],
        [1, 2, 5],
        [1, 7],
        [1, 2, 5],
        [1, 7],
        [2, 6],
    ])
);
// we can use simple JS object also to store unique elements  like { "[1, 1, 6]" : [1, 1, 6]  }
//resource - https://hackinbits.com/articles/how-to-iterate-a-map-in-javascript---map-part-2
Related