hol*_*ard 5 javascript arrays duplicates coordinates multidimensional-array
我有一个看起来像这样的数组:
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] ]
Run Code Online (Sandbox Code Playgroud)
第5行的纬度与第3行的相同,但它们具有不同的经度,因此不是重复的.
纬度和经度在第3行和第6行都是相同的,因此是重复的,应该删除一个.
geo*_*org 12
这个问题的难点在于,即使它们包含相同的值,不同的数组也不会相等.因此直接比较方法就好indexOf不行.
以下模式可能有助于解决此问题.编写一个函数(或使用内置函数),将数组转换为标量值,并检查这些值是否在集合中是唯一的.
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;
})
}
Run Code Online (Sandbox Code Playgroud)
其中key是一个"哈希"函数,它将items(无论它们是什么)转换为可比较的标量值.在您的特定示例中,仅应用于Array.join数组似乎就足够了:
uniqueCoords = uniq(coordinates, [].join)
Run Code Online (Sandbox Code Playgroud)
您可以使用标准的javascript函数拼接.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你有数千个点,它将比你需要考虑首先对值排序,然后在一个循环中删除重复项,它将工作缓慢.
Kan*_*mar -1
我不确定坐标[][]数据类型。进行相应的比较。
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.
Run Code Online (Sandbox Code Playgroud)