1

I have an array of arrays.

let myArr = [[1,2,3],[1,2,3],[3,4,5],[5,6,7],[5,6,7]];

I want to filter all repeating arrays in myArr so it stores only unique ones:

let myArr = [[1,2,3],[3,4,5],[5,6,7]];

I thought that by converting myArr into a set it would clear all 'duplicate' values, however, it did not:

let mySet = new Set(myArr);
// Set is: {[1,2,3],[1,2,3],[3,4,5],[5,6,7],[5,6,7]}

How can I properly filter myArr to hold only unique elements?

1
  • 1
    equality for arrays is not well defined, for example, are these "equal": [1,2,3] vs [1,,2,,3]? Or [1,"2"] vs ["1",2]? Commented Nov 21, 2018 at 21:06

5 Answers 5

2

You could take stringed arrays as value for the set and map then the arrays back.

var array = [[1, 2, 3], [1, 2, 3], [3, 4, 5], [5, 6, 7], [5, 6, 7]],
    unique = Array.from(
        new Set(array.map(a => JSON.stringify(a))),
        json => JSON.parse(json)
    );
    
console.log(unique);

If you need the original arrays, then you could filter with a Set.

var array = [[1, 2, 3], [1, 2, 3], [3, 4, 5], [5, 6, 7], [5, 6, 7]],
    unique = array.filter(
        (s => a => (j => !s.has(j) || s.set(j))(JSON.stringify(a)))
        (new Set)
    );
    
console.log(unique);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use JSON to identify duplicates in a set and keep only the unique arrays in your list.

const elem_sets = new Set();
const result = arr.filter(item => !elem_sets.has(JSON.stringify(item)) ? elem_sets.add(JSON.stringify(item)) : false);

console.log(result);

Comments

0

Try this:

 function remove(myArr) {
    let s = new Set(myArr);
    let it = s.values();
    return Array.from(it);
}

Comments

0

You can also solve this with a single Array.reduce where you group on the Array.toString():

const data = [[1, 2, 3], [1, 2, 3], [3, 4, 5], [5, 6, 7], [5, 6, 7]]

const r = Object.values(data.reduce((r,c) => (r[c.toString()] = c, r), {}))

console.log(r)

Comments

0

With Lodash you can filter the Array:

const myArr = _.uniqWith(objects, _.isEqual);

And than convert to a Set with Vanilla JS:

const mySet = new Set(uniqueArr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.