如何从两个数组中去除重复值?(对象数组场景)
从一维数组与对象数组中提取唯一值
给定两个数组,需要对比后提取arr1中不存在于arr2的唯一值:
arr1 = [ 'Material', 'Style', 'Size', 'add another item', 'THIS IS A TEST OPTION', 'Title', 'Color', 'dfgdfs', 'teststststst', 'THIS IS A NEW OPTION' ] arr2 = [ { option: 'Title', product: [ [Object] ] }, { option: 'Style', product: [ [Object] ] }, { option: 'Material', product: [ [Object] ] }, { option: 'Size', product: [ [Object], [Object] ] }, { option: 'Color', product: [ [Object], [Object] ] }, { option: 'THIS IS A NEW OPTION', product: [ [Object] ] }, { option: 'THIS IS A TEST OPTION', product: [ [Object] ] }, { option: 'add another item', product: [ [Object] ] } ]
预期输出:
['dfgdfs','teststststst']
你之前尝试的方法问题所在:
第一种方法
arr1.filter(val => !arr2.includes(val)):arr2是对象数组,includes直接比较字符串和对象,永远不相等,判断完全无效。第二种方法:
arr1.filter((val, index) => { if (arr2[index]) { !arr2[index].option.includes(val); } });filter的回调必须返回布尔值,你这里没有返回值(默认undefined会被视为false),且用索引对应两个数组的元素逻辑错误——两个数组元素顺序不匹配。第三种方法:
arr1.filter((val, index) => { allUniqueOptions.forEach((option) => { !option.option.includes(val); }); });同样没有给
filter回调返回值,且forEach内部的判断无法传递结果给外部的filter。
正确解决方案
方法一:用Set提升查询效率
先提取arr2中所有option值存入Set,再用Set过滤arr1,查询效率更高:
// 提取arr2的所有option值到Set const arr2Options = new Set(arr2.map(item => item.option)); // 过滤arr1中不在Set里的值 const result = arr1.filter(val => !arr2Options.has(val)); console.log(result); // ['dfgdfs','teststststst']
方法二:直接用数组判断(适合小数据量)
如果数据量不大,用some直接判断arr2中是否存在对应option:
const result = arr1.filter(val => !arr2.some(item => item.option === val)); console.log(result); // ['dfgdfs','teststststst']
内容的提问来源于stack exchange,提问作者InquisitiveTom
相关产品推荐
相关产品推荐

