Home > other >  How to check whether an array of object is present in another array of object in Javascript
How to check whether an array of object is present in another array of object in Javascript

Time:07-26

I have two array like this

const arr1 = [{code: 'a', name: 'x'}];
const arr2 = [{code: 'a', name: 'x'}, {code: 'b', name: 'y'}];

Here I want to check the code vale in first array object is present in the second array's code value.

For this I tried like this but it returned false

arr1.every(item => arr2.includes(item))

How can I check the code value in first array object is present in the second array object

CodePudding user response:

You can do something like this

const arr1 = [{code: 'a', name: 'x'}];
const arr2 = [{code: 'a', name: 'x'}, {code: 'b', name: 'y'}];

const codeValues = new Set(arr2.map(({code}) => code));

const isPresent = arr1.some(item => codeValues.has(item.code));
console.log(isPresent);

  • Related