How to find first element of array matching a boolean condition in JavaScript?
arrays, javascript
Solution
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);
Problem
I'm wondering if there's a known, built-in/elegant way to find the first element of a JS array matching a given condition. A C# equivalent would be List.Find. So far I've been using a two-function combo like this: ``` // Returns the first element of an array that satisfies given predicate Array.prototype.findFirst = function (predicateCallback) { if (typeof predicateCallback !== 'function') { return undefined; } for (var i = 0; i < arr.length; i++) { if (i in this && predicateCallback(this[i])) return this[i]; } return undefined; }; // Check if element is not undefined && not null isNotNullNorUndefined = function (o) { return (typeof (o) !== 'undefined' && o !== null); }; ``` And then I can use: ``` var result = someArray.findFirst(isNotNullNorUndefined); ``` But since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this? I imagine lots of people have to implement stuff like this all the time...