DEV Community

Cover image for Array.some() - for testing that at least one item meets a condition
Dillion Megida
Dillion Megida

Posted on • Edited on

Array.some() - for testing that at least one item meets a condition

This article is the sixth of the Array Method Series. In this article, I will explain what the some Array method is.

What is the Some Method?

The some method of arrays is a higher-order function that tests if at least one item in the array meets a certain condition. If one item meets it, it returns true, and if no item meets it, it returns false.

This method does not modify the array. It only loops through and applies a condition on each item until it finds the one that matches. This means that if it finds an element that matches, it doesn't continue looping the remaining items in the array. It immediately returns true.

Syntax of the Some Method

array.some(function(item, index, array){
  // condition to test item with
  // return true or false
})
Enter fullscreen mode Exit fullscreen mode

The callbackFunction passed to the some method is applied to each item in the array until it finds the item that matches the condition in the function.

The arguments passed to the callback function in each loop are the item, the index of the item, and the original array.

Without the Some Method

The some method is an abstracted function that does a quick check and stops at the first item that passes a certain criterion. Here's an example imitating the some method:

const array = [1, 2, 3, 4, 5, 6, 7, 8]

let hasEvenNumber = false

for (let i = 0; i < array.length; i++) {
  const item = array[i]
  console.log(item)
  if (item % 2 === 0) {
    hasEvenNumber = true
    break
  }
}

console.log(hasEvenNumber)
// 1
// 2
// true
Enter fullscreen mode Exit fullscreen mode

This loop approach is similar to what the some method does in the background. It loops through each item, and when it finds the item that matches the specified condition, it stops the loop and returns true.

With the Some Method

Here's how you achieve the previous result with some:

const array = [1, 2, 3, 4, 5, 6, 7, 8]

const hasEvenNumber = array.some(item => {
  console.log(item)
  return item % 2 === 0
})

console.log(hasEvenNumber)
// 1
// 2
// true
Enter fullscreen mode Exit fullscreen mode

From the result, you can see the first log 1, which is the item in the first loop, 2, the item in the second loop, and since 2 matches the condition, some stops the loop and immediately returns true.

The some method is useful when you have different values in an array, and you want to assert that at least one item meets a condition or that no items meet a condition.

Top comments (4)

Collapse
 
code_with_ali profile image
AlixaProDev

Love this series.

Collapse
 
dillionmegida profile image
Dillion Megida

I'm glad you do :)

Collapse
 
dashka22 profile image
Dashka Baasan

Thanks a lot

Collapse
 
dillionmegida profile image
Dillion Megida

You're welcome