18

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]]
3
  • Iterate over every entry in the array, looking for duplicates. it's the only way. Commented Dec 2, 2013 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? Commented Dec 2, 2013 at 23:15
  • 1
    This question is fairly outdated. Newer answers exist here: stackoverflow.com/questions/57562611/… Commented Aug 20, 2019 at 16:27

3 Answers 3

30

const 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;
}

const uniques = multiDimensionalUnique(arr);
console.log(uniques);

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.

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

Comments

14

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.

2 Comments

here is modified short code arr.map(JSON.stringify).filter((el, i , ar)=> i === ar.indexOf(el)).map(JSON.parse)
Nice! Answer updated w/ your version.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.