javascript 如何从多维数组中删除重复项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20339466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove duplicates from multidimensional array?
提问by Micha? Kalinowski
I have a multidimensional 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!
谢谢!
回答by Stephen
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.
就像你提到的那样,另一个问题只涉及一维数组......你可以通过 indexOf 找到它。这样就很容易了。多维数组并不那么容易,因为 indexOf 不适用于在内部查找数组。
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.
我能想到的最直接的方法是序列化数组值,并存储它是否已经找到。执行类似的操作可能会更快stringified = arr[i][0]+":"+arr[i][1]
,但是您将自己限制为只有两个键。
回答by Matt
This requires JavaScript 1.7:
这需要 JavaScript 1.7:
var arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];
arr.map(JSON.stringify).reverse().filter(function (e, i, a) {
return a.indexOf(e, i+1) === -1;
}).reverse().map(JSON.parse) // [[7,3], [3,8], [1,2]]
回答by qiu-deqing
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);