嗨,我是Java脚本的新手,我想要以下情况的解决方案。我有一个多维坐标数组
var coordinateArr = [ [[45.56,45.57],[44.36,44.37]],
[[42.26,42.37],[42.46,42.57]],
[[41.56,41.57],[41.36,41.37],[41.26,41.27]]
];
我还有另一个多维数组,例如
var anotherArr = [ [[41.56,41.57],[41.36,41.37],[41.26,41.27]],
[[42.26,42.37],[42.46,42.57]]
];
现在,我想像这样从coordinateArr中提取不匹配的值
var unmatchedArr= [[[45.56,45.57],[44.36,44.37]]];
我该怎么做?
答案 0 :(得分:3)
Javascript通过引用进行数组比较,因此除非一组是同一对象,否则您不能简单地测试一组中的数组是否在另一组中。您需要测试每个值,或者将数组转换为按值进行比较的值,例如字符串。对于数组,可以使用JSON.stringify
。如果您从Set
中提取了anotherArr
,则可以将filter
与Set.has()
var coordinateArr = [ [[45.56,45.57],[44.36,44.37]],
[[42.26,42.37],[42.46,42.57]],
[[41.56,41.57],[41.36,41.37],[41.26,41.27]]
];
var anotherArr = [ [[41.56,41.57],[41.36,41.37],[41.26,41.27]],
[[42.26,42.37],[42.46,42.57]]
];
let keys = new Set(anotherArr.map(JSON.stringify))
let filtered = coordinateArr.filter(arr => !keys.has(JSON.stringify(arr)))
console.log(filtered)
答案 1 :(得分:1)
尝试filter
找出另一个数组中未include
的数组元素:
var coordinateArr = [
[
[45.56, 45.57],
[44.36, 44.37]
],
[
[42.26, 42.37],
[42.46, 42.57]
],
[
[41.56, 41.57],
[41.36, 41.37],
[41.26, 41.27]
]
];
var anotherArr = [
[
[41.56, 41.57],
[41.36, 41.37],
[41.26, 41.27]
],
[
[42.26, 42.37],
[42.46, 42.57]
]
];
var unmatchedArr = coordinateArr.filter(e => !anotherArr.includes(e));
console.log(unmatchedArr);