17

I have a two-dimensional array:

[[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]]

Is there any smart way to remove duplicated elements from this? It should return such array:

[[7,3], [3,8], [1,2]]

Thanks!

OBezzad
  • 145
  • 1
  • 9
Michał Kalinowski
  • 451
  • 2
  • 6
  • 10
  • Iterate over every entry in the array, looking for duplicates. it's the only way. – Kevin B Dec 02 '13 at 23:12
  • Does order matter? e.g. what about `[[7, 3], [3, 7]]`? Do you want to treat that as two distinct elements, or duplicate elements? – Sean Dec 02 '13 at 23:15
  • 1
    This question is fairly outdated. Newer answers exist here: https://stackoverflow.com/questions/57562611/how-to-get-distinct-values-from-an-array-of-arrays-in-javascript-using-the-filte/57562822#57562822 – Seph Reed Aug 20 '19 at 16:27

3 Answers3

27
arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

function multiDimensionalUnique(arr) {
    var uniques = [];
    var itemsFound = {};
    for(var i = 0, l = arr.length; i < l; i++) {
        var stringified = JSON.stringify(arr[i]);
        if(itemsFound[stringified]) { continue; }
        uniques.push(arr[i]);
        itemsFound[stringified] = true;
    }
    return uniques;
}

multiDimensionalUnique(arr);

Explaination:

Like you had mentioned, the other question only dealt with single dimension arrays.. which you can find via indexOf. That makes it easy. Multidimensional arrays are not so easy, as indexOf doesn't work with finding arrays inside.

The most straightforward way that I could think of was to serialize the array value, and store whether or not it had already been found. It may be faster to do something like stringified = arr[i][0]+":"+arr[i][1], but then you limit yourself to only two keys.

Stephen
  • 5,362
  • 1
  • 22
  • 33
13

This requires JavaScript 1.7:

var arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

arr.map(JSON.stringify).filter((e,i,a) => i === a.indexOf(e)).map(JSON.parse)
// [[7,3], [3,8], [1,2]]

Credit goes to jsN00b for shortest version.

Matt
  • 20,108
  • 1
  • 57
  • 70
1
var origin = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

function arrayEqual(a, b) {
    if (a.length !== b.length) { return false; }
    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) {
            return false;
        }
    }
    return true;
}

function contains(array, item) {
    for (var i = 0; i < array.length; ++i) {
        if (arrayEqual(array[i], item)) {
            return true;
        }
    }
    return false;
}

function normalize(array) {
    var result = [];
    for (var i = 0; i < array.length; ++i) {
        if (!contains(result, array[i])) {
            result.push(array[i]);
        }
    }
    return result;
}

var result = normalize(origin);
console.log(result);

http://jsfiddle.net/2UQH6/

qiu-deqing
  • 1,323
  • 7
  • 13