Get first element of a collection that matches iterator function

ducin picture ducin · Oct 21, 2013 · Viewed 51.7k times · Source

I would like to achieve something like _.first with _.filter, that is, having a collection of elements, I'd like to get the first one (if exists) that matches a truth test (iterator).

For example, given an array like the following:

var arr = [{a: 1}, {a: 5}, {a: 9}, {a: 11}, {a: 15}]

I would like to getthe first (and only first) element that matches my custom function:

_.filterFirst(arr, function(el) { return el.a > 10; }); // make it

So far:

_.first(arr) == {a:1}
_.filter(arr, function(...)) == [{a:11}, {a:15}]

Is there a clean solution to do this which is better than _.first(_.filter(arr, iterator))?

Answer

Tahir Hassan picture Tahir Hassan · Oct 21, 2013

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.