iterate over an array of objects and check in each item if its property name has a value that is present in the array2 array, if not exclude the object from the original array in javascript

index.tsx
// Array of objects
const array1 = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'orange', color: 'orange' }
];

// Array of values to check against
const array2 = ['apple', 'orange'];

const resultArray = array1.filter(obj => array2.includes(obj.name));

console.log(resultArray);
328 chars
14 lines

In this example, we iterate over the array1 using the filter method and keep only the objects whose name property is included in the array2. This results in a resultArray containing only the objects with names that are present in array2.

related categories

gistlibby LogSnag