49

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

5
  • 1
    Have a look at the find function underscorejs.org/#find Oct 21, 2013 at 14:52
  • Why not just _.filter(arr, iterator)[0]
    – levi
    Oct 21, 2013 at 14:54
  • 1
    @levi because it consumes more CPU than it should.
    – ducin
    Oct 21, 2013 at 18:56
  • Why not just _.filter(arr, iterator)[0] Jul 16, 2018 at 11:38
  • @RobertRavikumar have you ever heard of performance? Or algorithmic complexity? Here you go. BTW that question is 5-years old
    – ducin
    Jul 16, 2018 at 20:43

4 Answers 4

89

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.

2
  • 2
    precisely! _.find is what I need!
    – ducin
    Oct 21, 2013 at 15:49
  • ...or Array.prototype.find(), but it's not supported by IE. One can use a polyfill though. Note that just translating ES2015+ to ES5 would not be enough. Jun 27, 2017 at 11:39
2

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.

0

"_.find" is a good solution.

An alternative solution, maybe faster, is to use "Array.prototype.every" in this way:

var match;
arr.every(function(x) { if (x.a > 10) { match = x; return false;} return true; })
0

_.find - in lodash: https://lodash.com/docs/4.17.10#find

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'

// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'

// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', false]);
// => object for 'fred'

// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.