Sometimes we need to take an array and apply some method(s) to its elements so that we get a new array with modified elements.
Here in this module we will discuss the some()
method of the JavaScript array.
some()
method check at least one of the element passes the test implemented by the function. This method executes the function once for each element present in the array and returns a boolean value.
If it found an element in the Array which returns true for the function, it will also return true. If it doesn't find any element which returns true for the implemented function, it will return false.
point to remember
some()
will always only return true/false.some()
will not modify the main input Array.- In
some()
, if Array having no element, this function will also not execute.
Let's understand this with some example :
Check if any even number is there in this given array :
numbers = [13,57,985,365,458,23];
var numbers = [13,57,985,365,458,23];
function checkEven(x){
return x % 2 === 0;
}
const result = numbers.some(checkEven);
console.log(result); // -> true;
Find if any of the given ages are more than 50.
ages = [2,34,49,9,24,7]
var ages = [2,34,49,9,24,7];
function checkAge(x){
return x >50;
}
var ageResult = ages.some(checkAge) ;
console.log(ageResult); // -> false;
achieve this using the Arrow function:
var numbers = [13,57,985,365,458,23];
console.log(numbers.some(x => x%2 === 0 )); // -> true.
var ages = [2,34,49,9,24,7];
console.log(ages.some(x => x>50)); // -> false;