简体   繁体   English

如何从 JS 中的 2 个对象数组中找到唯一元素

[英]How to find unique elements from 2 array of objects in JS

I have following 2 arrays,我有以下 2 个 arrays,

I want to compare empIds value with allEmps id value and want to push unique value to a new array,我想将 empIds 值与 allEmps id 值进行比较,并希望将唯一值推送到新数组,

var empIds = [ 123, 321 ];

var allEmps = [ [{id: 123, name: 'Raj'}], [{id: 321, name: 'Raju'}], [{id: 931, name: 'Rahul'}];

Expected output:
                [{id: 931, name: 'Rahul'}]

My try,我的尝试,

gridData = [];
empIds.forEach(id => {
  allEmps.forEach(series => {
    if (series[0].id !== id) {
      gridData.push(series[0]);
    }
  });
});

But these code is giving duplicate data also, can anyone pls correct my code.Thanks.但是这些代码也给出了重复的数据,任何人都可以纠正我的代码。谢谢。

Duplicates are caused by iterating over empIds and over allEmps each time.重复是由每次迭代empIdsallEmps引起的。

Try changing the order and for each employee record checking if it's ID is not in empIds尝试更改订单并检查每个员工记录的 ID 是否不在empIds

gridData = [];
allEmps.forEach(series => {
  if (empIds.indexOf(series[0].id) === -1) { // ID not found in empIds
    gridData.push(series[0]);
  }
});
// gridData = [ {id: 931, name: "Rahul"} ]

Try this:尝试这个:

var empIds = [ 123, 321 ];
var allEmps = [ [{id: 123, name: 'Raj'}], [{id: 321, name: 'Raju'}], [{id: 931, name: 'Rahul'}];

var gridData = allEmps.map(arr => arr[0]).filter(emp => !empIds.includes(emp.id)) 

You can do it by steps:您可以按以下步骤进行:

var objs = allEmps.map(arr => arr[0]) 
// returns "[{"id":123,"name":"Raj"},{"id":321,"name":"Raju"},{"id":931,"name":"Rahul"}]"

You don't need to have array inside the array.您不需要在数组中包含数组。 Then filter the ones that are not part of empIds:然后过滤不属于 empIds 的那些:

objs.filter(emp => !empIds.includes(emp.id)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM