JavaScript Array some() Method

JavaScript Array some() method is used to check whether at least one element in an array passes the given test function.

This method does not modify the original array.

Syntax

array.some(callback(element, index, arr), thisValue)

Parameters

function(required): It is a function that tests each element of the array. It can take up to three arguments:

  1. element(required): The value of the current element.
  2. index(optional): The index of the current element.
  3. arr(optional): The array objects the current element belongs to.

thisValue(optional): It is the value to be passed to the function to be used as its “this” value. If the thisValue parameter is empty, the value “undefined” will be given as its “this” value.

Return Value

It returns true if at least one element passes the test and false otherwise.

Visual RepresentationVisual Representation of JavaScript Array some() Method

Example 1: How to Use Array some() Method

function isGreaterThan(element) {
 return element > 100;
 }
 
 let arr = [12, 79, 44, 788, 120] 
 let check = arr.some(isGreaterThan);
 console.log(check);

Output

true

Example 2: Using the Arrow function Visual Representation of Using Arrow() function with some()

let arr = [12, 79, 44, 788, 120] 

const lessThan = (currentValue) => currentValue < 10

console.log(arr.some(lessThan))

const allEven = (currentValue) => currentValue % 2 === 0

console.log(arr.some(allEven))

Output

false
true

Example 3: Checking if a value exists in an array

const cars = ["bmw", "mercedez", "audi", "jaguar"];

function checkAvailability(arr, val) {
  return arr.some((arrVal) => val === arrVal);
}

console.log(checkAvailability(cars, "bmw"));
console.log(checkAvailability(cars, "bentley"));

Output

true
false

In the above example, it checks If “bmw” and “bentley” are present in the cars array. In the first case, it returns true because “bmw” is present in cars array, while it returns false for the second case.

Example 4: Using sparse arraysVisual Representation of Using some() on sparse arrays

let sparseArr = [12, , 44, , 120]
console.log(sparseArr.some((x) => x === undefined));
console.log(sparseArr.some((x) => x !== 1));

Output

false
true

Example 5: Check a number within a range

let data = [12, 79, 44, 788, 120];

const range = {
  min: 100,
  max: 1000
};

let result = data.some(function (e) {
  return e >= this.min && e <= this.max;
}, range);

console.log(result);

Output

true

We check each element against the min and max numbers in this example. If it satisfies the condition, then it returns true otherwise false.

Browser compatibility

  • Google Chrome 1 above
  • Edge 12 and above
  • Firefox 1.5 and above
  • Opera 9.5 and above
  • Safari 3 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.