javascript - 如何从2个javascript数组中获取唯一记录?

标签 javascript typescript ecmascript-6

我有两个数组。其中几乎没有共同的值(value)观。我想过滤掉这些项目。我尝试了 es6 indexOfincludes 运算符,但没有成功。

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#hasO(1),但相同逻辑的数组方法是 O(n)

关于javascript - 如何从2个javascript数组中获取唯一记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60181789/

相关文章:

javascript - 从数组中删除除 2 个具有特定属性的对象之外的所有对象

c# - JSON 数据结构 - JSON 到对象 - 最佳实践

javascript - Typescript 对象索引器和与索引器类型不匹配的键

javascript - ReactJS:使用 map 渲染带有键的对象

javascript - Webpack:index.html 上未定义导出默认类

javascript - 语义 UI React : How to Hide Suggested Text from Search Box

javascript - 将集合转换为对象

javascript - 工作时间超过 25 天的 Node 的调度程序。

angular - 无法绑定(bind)到 'ngModel',因为它不是 'textarea' 的已知属性

javascript - 如何在React Native不同组件中设置State?