How to find first element of array matching a boolean condition in JavaScript?
As of ECMAScript 6, you can use Array.prototype.find
for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.
For example, x
below is 106
:
const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
return el > 105;
});
console.log(x);
If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find
and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).
What about using filter and getting the first index from the resulting array?
var result = someArray.filter(isNotNullNorUndefined)[0];
Since ES6 there is the native find
method for arrays; this stops enumerating the array once it finds the first match and returns the value.
const result = someArray.find(isNotNullNorUndefined);
Old answer:
I have to post an answer to stop these filter
suggestions :-)
since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this?
You can use the some
Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met. So we have to amend it a little:
function find(arr, test, ctx) {
var result = null;
arr.some(function(el, i) {
return test.call(ctx, el, i, arr) ? ((result = el), true) : false;
});
return result;
}
var result = find(someArray, isNotNullNorUndefined);