How to remove duplicates from a two-dimensional array? [closed]

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.

Leave a Comment