Get first element of a collection that matches iterator function

Adding the standard JavaScript Array.prototype.find method, as just the old answers would leave newcomers ill informed:

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); 
// expected output: 12

The example is from the above linked MDN page. There's also an Array.prototype.findIndex method that returns the index of where the predicate yielded true, rather than the array element of that index.

These methods are in ES2015 ie. 5 years old and are in pretty much all of the browsers people use, see this caniuse link.


You can use find:

Looks through each value in the list, returning the first one that passes a truth test (iterator), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.

Using your example:

var g = _.find(arr, function (x) { return x.a > 10 })

See the main page: http://underscorejs.org

Another thing to note (which might be your question) is the chain function to join calls together:

var g = _.chain(arr).filter(function (x) { return x.a > 10 }).first().value()

Notice the calls to filter and `first' which can follow each other without any nesting.