ES6 - Array some method

ES6 JavaScript

In this ES6 tutorial we are going to learn about the array some method. So, let's get started.

We use the some method to loop over the elements of an array and it returns true if at least one element of the array satisfy the given condition. If none of the elements satisfy the condition then it returns false.

Checking even number in an array

Let's say we have an array of integers and we want to know if the array contains at least one even number.

Let's see how to solve this problem using for loop.

const arr = [1, 3, 5, 8, 9];
let foundEven = false;
for(let i = 0; i < arr.length && !foundEven; i++) {
  if(arr[i] % 2 === 0) {
    foundEven = true;
  }
}
console.log(foundError);

We can achieve the same result using some method which simplifies the above code.

const arr = [1, 3, 5, 8, 9];
const evenNumberExists = arr.some(v => v % 2 === 0);
console.log(evenNumberExists);

Alright, this brings us to the end of this tutorial. Have fun learning.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT