Skip to content
Advertisement

Get first element of a collection that matches iterator function

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement