问题描述
我有一个二维数组:
[[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]]
谢谢!
推荐答案
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);
说明:
就像你提到的,另一个问题只涉及一维数组..你可以通过 indexOf 找到.这样就很容易了.多维数组不是那么容易,因为 indexOf 不适用于查找内部数组.
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.
我能想到的最直接的方法是序列化数组值,并存储它是否已经找到.执行诸如 stringified = arr[i][0]+":"+arr[i][1]
之类的操作可能会更快,但是您将自己限制为只有两个键.
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.
这篇关于如何从二维数组中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!