我有两个数组。其中几乎没有共同的值(value)观。我想过滤掉这些项目。我尝试了 es6
indexOf
和 includes
运算符,但没有成功。
arr1 = [
["Test1", 20, "table", "Sample1", "NA"],
["Test2", 20, "table", "Sample2", "NA"],
["Test3", 20, "table", "Sample3", "NA"],
["Test4", 20, "table", "Sample4", "NA"],
["Test5", 20, "table", "Sample5", "NA"]
];
arr2 = [
["Test2", 20, "table", "Sample2", "NA"],
["Test4", 20, "table", "Sample4", "NA"],
["Test5", 20, "table", "Sample5", "NA"],
["Test6", 20, "table", "Sample6", "NA"],
["Test7", 20, "table", "Sample7", "NA"]
];
let unique = arr2.filter((item, i, ar) => arr1.indexOf(item) === -1);
console.log(unique); //returns all 5
let result = [...arr1, ...unique];
console.log('length is:', result.length); //length should be 7 but its 10
最佳答案
创建一组字符串化的子数组。根据当前字符串化子数组是否包含在 other 数组的 Set 中来过滤两个数组:
const arr1 = [
["Test1", 20, "table", "Sample1", "NA"],
["Test2", 20, "table", "Sample2", "NA"],
["Test3", 20, "table", "Sample3", "NA"],
["Test4", 20, "table", "Sample4", "NA"],
["Test5", 20, "table", "Sample5", "NA"]
];
const arr2 = [
["Test2", 20, "table", "Sample2", "NA"],
["Test4", 20, "table", "Sample4", "NA"],
["Test5", 20, "table", "Sample5", "NA"],
["Test6", 20, "table", "Sample6", "NA"],
["Test7", 20, "table", "Sample7", "NA"]
];
const set1 = new Set(arr1.map(JSON.stringify));
const set2 = new Set(arr2.map(JSON.stringify));
const unique1 = arr1.filter(subarr => !set2.has(JSON.stringify(subarr)));
const unique2 = arr2.filter(subarr => !set1.has(JSON.stringify(subarr)));
console.log(unique1);
console.log(unique2);
我将数组转换为集合以降低计算复杂度 - Set#has
是 O(1)
,但相同逻辑的数组方法是 O(n)
。
关于javascript - 如何从2个javascript数组中获取唯一记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60181789/