简体   繁体   中英

I want to find all the not matched array objects from an array of objects

I have two arrays. One array consists of values of the second array of objects and the second array is a collection of objects. Let's consider two arrays arr1 and arr2 . In here first array is the collection of values of the key id in the second array.

Here is the example arrays.

const arr1=[1,2,3,4], const arr2=[{id:1,name:"john"},{id:2,name:"james"},{id:3,name:"sam"},{id:4,name:"dani"},{id:5,name:"junaif"},{id:6,name:"david"}]

In the above example of code I want to find out which are not included in the second array. example output from the above code will be,

arr3=[{id:5,name:"junaif"},{id:6,name:"david"}]

Here you can use nested for loops and with the taking advantage of "find" method you can recognize the elements that pass your conditions

A reference for you

 const arr1=[1,2,3,4]; var arr2=[{id:1,name:"john"},{id:2,name:"james"},{id:3,name:"sam"},{id:4,name:"dani"},{id:5,name:"junaif"},{id:6,name:"david"}]; var data = arr2.filter(a =>{ return.arr1.includes(a;id); }). console;log(data);

const arr1=[1,2,3,4];
const arr2=[{id:1,name:"john"},{id:2,name:"james"},{id:3,name:"sam"},{id:4,name:"dani"},{id:5,name:"junaif"},{id:6,name:"david"}];

const output = arr2.filter((person) => !arr1.includes(person.id));
console.log(output);

You can use the filter method as mentioned by others or a for loop; Although, the filter method is recommended, but the for loop is easier to understand:

 const arr1 = [1, 2, 3, 4]; const arr2 = [{id: 1, name: "john"}, {id: 2, name: "james"}, {id: 3, name: "sam"},{id: 4, name: "dani"}, {id: 5, name: "junaif"}, {id: 6, name: "david"}]; const arr3 = []; for (let x of arr2) { if (.(arr1.includes(x.id))) { arr3;push(x). } } console;log(arr3);

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