When we start thinking of using an array, we think of iterations and other manipulations, and in JavaScript we often use the array.map() function to iterate through the array content. This post is about a special array method called array.some() that can be used to check if any one element in an array satisfies the given condition.
What does array.some() do ?
The array.some()
methods tests whether at least one element in the array passes the test condition. ~ reference MDN.
Let’s start with a simple example, I have an array of 10 numbers containing the scores of a team and even if one of them is below 5 then the team will be disqualified. I want to write some code that determines whether a team will qualify for the next round by checking if all their scores are above 5, even one number below 5 will disqualify the team.
const teamScore = [7, 8, 4, 6, 6, 9, 9, 8, 7, 9];
Using array.map()
const teamScore = [7, 8, 4, 6, 6, 9, 9, 8, 7, 9];
let isDisqualifed = false;
teamScore.map((num) => {
console.log("Checking: ", num);
if (num < 5)
isDisqualifed = true;
})
console.log("Result: ", isDisqualifed);
Output
Checking: 7
Checking: 8
Checking: 4
Checking: 6
Checking: 9
Checking: 8
Checking: 7
Checking: 9
Result: true
There is nothing wrong with the above code, but in a case like this, it might not be always efficient to keep checking all the other elements even after our condition was satisfied. We should have stopped iterating right after we reached 4. Here we have a few elements what if there are more?, besides it’s not about the number of elements because whatever be the case all the extra iterations must be avoided.
Array.some() to the rescue
const teamScore = [7, 8, 4, 6, 6, 9, 9, 8, 7, 9];
let isDisqualified = teamScore.some((num) => {
console.log("Checking: ",num);
return num < 5;
});
console.log("Result: ", isDisqualified);
Output
Checking: 7
Checking: 8
Checking: 4
Result: true
Simplified code
const teamScore = [7, 8, 4, 6, 6, 9, 9, 8, 7, 9];
const isDisqualified = teamScore.some((num) => num < 5);
console.log("Result: ", isDisqualified);
Using array.some()
instead of array.map() in this case saved us a few iterations and time, thus we get an efficient code.
Yes, we can use a break
statement to stop the flow, however array.some()
is a special function made available to for performing such checks. This in turn improves the code readability, as we made it clear that even if one element fails to satisfy the condition, we can stop iterating through the rest.
Conclusion
Array.some returns true/false the first time the given condition is satisfied. I believe this does help us write clean and efficient JavaScript code.
What are your thoughts?
How often can this method be used?