How to remove duplicates from a two-dimensional array? [closed]
Solution 1:
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.
Solution 2:
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]]
Solution 3:
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/