我有以下代码不适用于嵌套数组(尽管它适用于简单数组):
var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0]];
var duplicatesArray = array1.filter(function(val) {
return array2.indexOf(val) !== -1;
});
console.log(duplicatesArray); // should return [["501", 1800, "floorsRegion1", 0]]; but it doesn't currently
如果我不是简单的嵌套数组,而是简单的数字或字符串,那么它将起作用,并且“ duplicatesArray”将包含重复对象。但是JS不会将整个数组作为值进行比较,因此我的代码无法正常工作。
只有val [0]对于在这些嵌套数组中进行比较是必不可少的,但结果数组必须包含整个嵌套数组才能重复。
我找到了几种类似的解决方案,但是它们删除了重复对象,而不是返回带有重复对象的数组。
答案 0 :(得分:3)
如果您只关心索引为0的项目,则可以使用some
进行过滤,并检查array2
中某项目的ID,它的第一个值等于正在过滤的当前项目的第一个值:< / p>
var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0]];
let filtered = array1.filter(arr => array2.some(arr2 => arr2[0] == arr[0]))
console.log(filtered)
// with two items in array2:
array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
array2 = [["501", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
filtered = array1.filter(arr => array2.some(arr2 => arr2[0] == arr[0]))
console.log(filtered)
这不是很有效,因为它看起来像array2中的array1中的每个项目。如果数组很大,则值得使用允许更快查找的对象或Set进行查找。像这样:
var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
let known = new Set(array2.map(item => item[0]))
let filtered = array1.filter(arr => known.has(arr[0]))
console.log(filtered)