简体   繁体   中英

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

I have following 2 arrays,

I want to compare empIds value with allEmps id value and want to push unique value to a new array,

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.

Try changing the order and for each employee record checking if it's ID is not in 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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