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"}]
CodePudding user response:
Here you can use nested for loops and with the taking advantage of "find" method you can recognize the elements that pass your conditions
CodePudding user response:
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);
CodePudding user response:
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);
CodePudding user response:
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);