Javascript Array some()

Introduction

Javascript array some() method checks whether at least one element passes the provided function.

It returns a Boolean value.

Calling this method on an empty array returns false for any condition.

some() does not change the array.

arr.some(callback(element[, index[, array]])[, thisArg])
Parameter
Optional
Meaning
callback




Not




A function to test for each element
It takes three arguments:
element - the current element being processed.
index - Optional, the index of the current element.
array - Optional, The array itself.
thisArg
Optional
A value to use as this when executing callback.

The range of elements processed by some() is set before the first invocation of callback.

The following example tests whether any element in the array is bigger than 10.

function isBiggerThan10(element, index, array) {
  return element > 10;
}

let a = [12, 5, 8, 1, 4].some(isBiggerThan10);  
console.log(a);/*from   www  . j  av  a2 s . c o m*/
a = [0, 5, 8, 1, 4].some(isBiggerThan10);
console.log(a);

Testing array elements using arrow functions

let a = [1, 5, 8, 1, 4].some(x => x > 10);  
console.log(a);//from   w  w  w .  j a v a 2 s .c  o  m

a = [2, 5, 8, 1, 42].some(x => x > 10); 
console.log(a);

Checking whether a value exists in an array

const languages = ['HTML', 'CSS', 'Java', 'Javascript'];

function checkAvailability(arr, val) {
  return arr.some(function(arrVal) {
    return val === arrVal;
  });// w w  w . ja va  2s.co m
}

let a = checkAvailability(languages, 'C++');   
console.log(a);
a = checkAvailability(languages, 'CSS'); // true
console.log(a);

Checking whether a value exists using an arrow function

const languages = ['HTML', 'CSS', 'Javascript', 'Java'];

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

let a = checkAvailability(languages, 'C++');
console.log(a);/*from ww  w.j  av  a  2s .  co  m*/

a = checkAvailability(languages, 'CSS'); // true
console.log(a);

Converting any value to Boolean

More example:

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];

let everyResult = numbers.every((item, index, array) => item > 2);
console.log(everyResult); // false 

let someResult = numbers.some((item, index, array) => item > 2);
console.log(someResult); // true 



PreviousNext

Related