Skip to content
Advertisement

compare an array and object to see if item exists

I have the following: An array

const myArray = ['john', 'frank', 'paul'];

then I have an array of objects

const myObjectArray = [
    {name: 'nery', age: 34, present: true},
    {name: 'john', age: 15, present: false},
    etc
]

How can I check if myArray value is found in the myObjectArray? I thought about looping through myArray and then in each iteration looping through myObjectArray to see if it is present. However this seems so 2001.

Any ideas?

Advertisement

Answer

if you want to check if an item from first array is in the name of second array use some to return a boolean

const myArray = ["john", "frank", "paul"];

const myObjectArray = [
  { name: "nery", age: 34, present: true },
  { name: "john", age: 15, present: false },
];
res = myObjectArray.some((o) => myArray.includes(o.name));
console.log(res);

If you want to return the object that has same name from first array use filter

const myArray = ["john", "frank", "paul"];

const myObjectArray = [
  { name: "nery", age: 34, present: true },
  { name: "john", age: 15, present: false },
];
res = myObjectArray.filter((o) => myArray.includes(o.name));
console.log(res);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement