6

let's say I have an array of objects:

let arr = [
   {
    name: 'Jack',
    id: 1
   },
   {
    name: 'Gabriel',
    id: 2
   },
   {
    name: 'John',
    id: 3
   }
]

I need to check whether that array includes the name 'Jack' for example using:

if (arr.includes('Jack')) {
   // don't add name to arr

} else {
  // push name into the arr

}

but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?

0

1 Answer 1

15

Since you need to check the object property value in the array, you can try with Array​.prototype​.some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

let arr = [
   {
    name: 'Jack',
    id: 1
   },
   {
    name: 'Gabriel',
    id: 2
   },
   {
    name: 'John',
    id: 3
   }
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);

Sign up to request clarification or add additional context in comments.

2 Comments

For single value it is working. What if I need to check for array of values like ["John", "Jack"]]?
@UI_Brain, simply omit the property name - arr.some(i => i.includes('Jack'));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.