DEV Community

loading...
JS Mates

Check whether a condition is met at-least once in a JS array?

Paramanantham Harrison
Originally published at jsmates.com on ・1 min read

Let's have an array of authors,

const authors = [
  {
    name: 'Param'
  },
  {
    name: 'Joshua'
  }
];
Enter fullscreen mode Exit fullscreen mode

We need to check whether an author with the name Joshua exists in the array. It can be done in several ways. We are going to use modern ES6+ syntax using Array.some to find whether the author exists in the array.

// Check whether author Joshua present in the array
const isJoshuaFound = authors.some(({ name }) => name === 'Joshua');
console.log('Is Joshua an Author? -> ', isJoshuaFound);
Enter fullscreen mode Exit fullscreen mode

Now, let's check someone who is not in the array,

// Check whether author Harris present in the array
const isHarrisFound = authors.some(({ name }) => name === 'Harris');
console.log('Is Harris an Author? -> ', isHarrisFound);
Enter fullscreen mode Exit fullscreen mode

The advantage of using Array.some over other array method is, it will check until the first match exists. Then it breaks out of the loop.

For example, if you have an array of 100 elements, and the match happens at the 2nd element. Then Array.some won't iterate over the remaining element.

Discussion (0)