I recently starting to drop underscore/lodash overuse on (some of) my projects and realize that there's no full support of find method in browsers. What's the difference between ES6 method find and using .shift() over filter results
var user = users.find(function() { ... } );
or
var user = users.filter(function() { ... } ).shift();
I imagine there's obvious optimization over "find" method (stop iterating on fist match), but can I get unexpected results using second approach? Should I use the polyfill instead? Why?
The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to leaf. The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed.
Find and FilterThe find() method returns the first value that matches from the collection. Once it matches the value in findings, it will not check the remaining values in the array collection. The filter() method returns the matched values in an array from the collection.
find() here will be faster as your filter() method relies on find() anyway.
map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong.
Apart from the obvious (and noticeable) overhead, yes, the results might vary. filter
runs till the end of the array, and invokes its callback on every item; in contrast to find
which stops after having found one. When the callback throws an exception on one of these additionally iterated elements, the outcome is different.
I don't see any good reason not to use find
.
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