Array.some()
The Array.some() method returns a Boolean value based on whether or not at least one item in the provided array meets the supplied condition(s).
The Array.some()
method returns a Boolean value based on whether or not at least one item in the provided array meets the supplied condition(s).
Syntax
array.some(callbackFunction(element[, index[, array]])[, thisArg])
The Array.some()
method accepts a callback function as the first parameter.
Optional parameters include:
index
which provides the index of the current element being processed in the arrayarray
which is the current array being processedthisArg
which is the value to be used asthis
within the callback function
Real World Example
Let's imagine that a professor wants to quickly check whether or not anyone in their class got over 100% on their exam after their teaching assistant finished grading them:
const examScores = [88, 97, 59, 73, 77, 101, 95, 72, 84, 86, 81, 100, 69, 79, 91, 68, 76, 99];
examScores.some(score => score > 100); // returns true
// there's at least exam score greater than 100
The Traditional Alternative
Without the Array.some()
method, the professor would probably need to write some code like this:
const examScores = [88, 97, 59, 73, 77, 101, 95, 72, 84, 86, 81, 100, 69, 79, 91, 68, 76, 99];
const checkExamScores = (examScores) => {
let anyExamsOverOneHundred = false;
for (let i = 0; i < examScores.length; i++) {
if (examScores[i] > 100) {
anyExamsOverOneHundred = true
}
}
return anyExamsOverOneHundred;
}
checkExamScores(examScores);
Wrapping up ✅
As seen in the examples above, the Array.some()
method eliminates quite a bit of code when you simply need to check whether a condition has been met!
Stay Tuned 📺
If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]
. If you're enjoying my posts, please click here 📬 or subscribe below 👇!
Help us improve our content