比较对象javascript的两个数组并删除不相等的值

时间:2018-07-31 07:26:15

标签: javascript

我有两个对象数组。

   Size attribute
0     2        V2
1     3        V3
2     1        V1
3     4        V3

我想比较这些对象,我的最终结果将是

e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]

我尝试过

result = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11}]

但是得到了

let result = e.filter(o1 => f.some(o2 => o1.qId != o2.qId));

如何实现所需的输出?

4 个答案:

答案 0 :(得分:2)

您似乎应该过滤f,而不是e,因为result显示的是f而不是e的值。

为了使复杂度最小,请将e数组的qId转换为Set,以便首先进行快速查找。 (与Set的{​​{1}}复杂度相比,{O(1) s具有O(N)的查找时间)

.some

答案 1 :(得分:2)

我希望您需要比较qId。

let e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
let f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}]
let res = [];
f.forEach(fo => {
  e.forEach(eo => {
    if(fo.qId === eo.qId){
       res.push(fo)
    }
  })
})

console.log(res)

答案 2 :(得分:1)

您可以结合使用Array.filter()Array.some()来获得结果:

e = [{uniqueId:'',active:'a',qId:10},{uniqueId:'',active:'a',qId:11}]
f = [{uniqueId:50,active:'a',qId:10},{uniqueId:51,active:'a',qId:11},{uniqueId:52,active:'a',qId:13}];
var res = f.filter(fItem => e.some(({qId}) => fItem.qId === qId));
console.log(res);

答案 3 :(得分:0)

您可以检查数组e是否具有相同的qId值来过滤f

var e = [{ uniqueId: '', active: 'a', qId: 10 }, { uniqueId: '', active: 'a', qId: 11 }],
    f = [{ uniqueId: 50, active: 'a', qId: 10 }, { uniqueId: 51, active: 'a', qId: 11 }, { uniqueId: 52, active: 'a', qId: 13 }],
    result = f.filter(({ qId }) => e.some(o => o.qId === qId));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }