Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between find() and filter().shift() on javascript

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?

like image 823
neiker Avatar asked Nov 17 '15 14:11

neiker


People also ask

What is the difference between find and filter method in JavaScript?

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.

How do you use Find and filter in JavaScript?

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.

Which is faster filter or find?

find() here will be faster as your filter() method relies on find() anyway.

What is the difference between filter and map in JavaScript?

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.


1 Answers

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.

like image 55
Bergi Avatar answered Oct 30 '22 12:10

Bergi