How to remove duplicates from a two-dimensional array?
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.
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.
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/