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!
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.
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.
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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With