如何从多维数组中删除重复项? [英] How to remove duplicates from multidimensional array?

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

问题描述

我有一个多维数组:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆