从多维数组中删除重复的元素对 [英] Remove duplicate element pairs from multidimensional array

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

问题描述

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

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;
    })
}

其中 key 是一个散列"函数,可将 items(无论它们是什么)转换为可比较的标量值.在您的特定示例中,仅将 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天全站免登陆