Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 493
Michał Kalinowski Avatar asked Dec 02 '13 22:12

Michał Kalinowski


People also ask

How do you remove duplicates from a two-dimensional array?

we will follow following steps to create a PHP function that will remove duplicate values from multi dimentional array. Step 1:First we will use serialize() funtion to serialize the array. Then use map with php inbuilt function. Step 2: use unserialize() function to make the serialized string into a PHP value.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

How do you remove duplicates from a two-dimensional array in Java?

Remove Duplicates From Array Java in Unsorted Array If you have an unsorted array, you must first sort it. Use the Arrays. sort(arr) function to accomplish this. This is the second approach to remove duplicates from array Java.


2 Answers

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.

like image 161
Stephen Avatar answered Sep 27 '22 00:09

Stephen


This requires JavaScript 1.7:

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

arr.map(JSON.stringify).reverse().filter((e, i, a) => a.indexOf(e, i+1) === -1).reverse().map(JSON.parse) // [[7,3], [3,8], [1,2]]
like image 21
Matt Avatar answered Sep 27 '22 00:09

Matt