-1

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"}]

junaif
  • 51
  • 1
  • 5

3 Answers3

0

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 result = [];

for (let index = 0; index < arr2.length; index++) {
      const element = arr2[index];
      if(!arr1.find(q => q === element.id))
      {
          result.push(element);
      }
}

console.log(result)

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

0
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);
0

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);