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))
?
We can find the first element of an array that satisfies a given condition using the first(where:) method.
To get the first element of a Set, use destructuring assignment, e.g. const [first] = set . The destructuring assignment sets the variable to the first element of the Set.
Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array. slice(0, n); }; console.
The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With