卸下多维数组的重复元素对 [英] Remove duplicate element pairs from multidimensional array

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

问题描述

我有一个数组,看起来像这样:

I have an array that looks like this:

1.  coordinates = [ [16.343345, 35.123523],
2.                  [14.325423, 34.632723],
3.                  [15.231512, 35.426914],
4.                  [16.343345, 35.123523],
5.                  [15.231512, 32.426914] ]

在第5行的纬度相同第3行,但它们具有不同的经度,因此不重复。

The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.

两者的纬度和经度是在第3行和6是相同的,并因此重复和一个应被删除。

Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.

推荐答案

在这个问题上,不同的阵列根本不比较平等的,即使它们包含相同的值的困难。所以直接比较的方法,如的indexOf 将无法工作。

The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.

以下模式可能是解决这个有用。写的函数(或使用内置在一个),该转换阵列标量值,并检查是否这些值中的一组是唯一的。

The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.

uniq = function(items, key) {
    var set = {};
    return items.filter(function(item) {
        var k = key ? key.apply(item) : item;
        return k in set ? false : set[k] = true;
    })
}

其中,是一个哈希功能,转换项目(无论他们是)可比标量值。在你的特殊的例子,它似乎是不够的只是适用 Array.join 来数组:

where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:

uniqueCoords = uniq(coordinates, [].join)

这篇关于卸下多维数组的重复元素对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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