TheWebs TheWebs - 1 year ago 113
Javascript Question

using lodash unique on an array of arrays

I am not sure how to use this to remove duplicate arrays from the main array. so consider the following:

var arr = [
[0, 1],
[0, 1],
[2, 1],
];


The resulting array should look like:

var arr = [
[0, 1],
[2, 1],
];


The documentation makes sense for a single array of elements but not a 2d array.

Ideas?

Update, One small issue with some solutions:



The array to be turned unique might have:

var arr = [
[0, 1]
[0, 2]
[0, 3]
[0, 1]
[2, 1]
]


the array in side the array should have all value compared, so in the above example, it should spit out:

var arr = [
[0, 1]
[0, 2]
[0, 3]
[2, 1]
]


The duplicate being
[0, 1]

Answer Source

The easiest way would probably be to use uniq method and then convert the inner arrays to some string representation, JSON.stringify should be good enough solution.

var arr = [[0, 1], [0, 2], [0, 3], [0, 1], [2, 1]]
_.uniq(arr, function(item) { 
    return JSON.stringify(item); 
});
// [[0,1], [0,2], [0,3], [2,1]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download