本文介绍了如何从二维数组中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组:

[[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.

这篇关于如何从二维数组中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:35