How to find first element of array matching a boolean condition in JavaScript?

How to find first element of array matching a boolean condition in JavaScript?

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...

Solutions/Answers:

Solution 1:

Since ES6 there is the native find method for arrays.

const result = someArray.find(isNotNullNorUndefined);

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);

Solution 2:

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.

Related:  Adding code to a javascript function programmatically

For example, the expression below evaluates to 106.

[100,101,102,103,104,105,106,107,108,109].find(function (el) {
    return el > 105;
});

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).

Solution 3:

What about using filter and getting the first index from the resulting array?

var result = someArray.filter(isNotNullNorUndefined)[0];

Solution 4:

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it’s not hard to apply some trickery, such as the solution offered by Bergi’s answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Related:  How to get Mocha to fail a test

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don’t support offset searching either, so I’ve decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

Solution 5:

If you’re using underscore.js you can use its find and indexOf functions to get exactly what you want:

var index = _.indexOf(your_array, _.find(your_array, function (d) {
    return d === true;
}));

Documentation:

Related:  jQuery getJSON save result into variable [duplicate]

Solution 6:

Summary:

  • For finding the first element in an array which matches a boolean condition we can use the ES6 find()
  • find() is located on Array.prototype so it can be used on every array.
  • find() takes a callback where a boolean condition is tested. The function returns the value (not the index!)

Example:

const array = [4, 33, 8, 56, 23];

const found = array.find((element) => {
  return element > 50;
});

console.log(found);   //  56