2

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]

TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • 1
    [What](http://stackoverflow.com/help/on-topic) [have](http://stackoverflow.com/help/how-to-ask) [you tried](http://stackoverflow.com/help/mcve)? – rockerest Nov 03 '15 at 19:47
  • Will this help: [http://stackoverflow.com/questions/31740155/lodash-remove-duplicates-from-array](http://stackoverflow.com/questions/31740155/lodash-remove-duplicates-from-array) – 2174714 Nov 03 '15 at 19:48
  • @user2174714 Not exactly, Please see updated answer. – TheWebs Nov 03 '15 at 19:55

4 Answers4

4

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]]
Lukáš Havrlant
  • 4,134
  • 2
  • 13
  • 18
2

You would use the .uniq function in lodash:

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

var uniqueList = _.uniq(arr, function(item, key, a) { 
    return item.a;
});

The resulting array will look like:

//var arr = [Object: [0, 1], Object: [2, 1]];
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • I update my question with a small hitch that I caught when testing your concept. Could you take a look and see if yuor solution can be tweaked to make this work? – TheWebs Nov 03 '15 at 19:54
2

Sure, casting to JSON works, but it feels like we might be wasting resources. I'm using the following Lodash-code in Node.js:

const _ = require("lodash");

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

var uni = _.uniqWith(arr, _.isEqual);
console.log(uni);

Works like a charm, check the Repl here. More on uniqWith at the Lodash docs.

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
-1

It doesn't use lodash, not optimized I agree :

//remove duplicate array of array of arrays
Array.prototype.uniqueArray = function() {
    var uniqObj = {};
    this.forEach(function (item) {
        uniqObj[JSON.stringify(item)] = 1;
    });

    var uniqArray = [];
    for(var key in uniqObj) {
        if (uniqObj.hasOwnProperty(key)) {
            uniqArray.push(JSON.parse(key))
        }
    }
    return uniqArray;
};
Remy Mellet
  • 1,675
  • 20
  • 23