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

JavascriptEcmascript 6

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Use a polyfill; users.filter(function() { ... } ).shift(); is throwing cycles away while triggering unnecessary garbage collection.

  • filter scans the entire array and creates another array
  • shift now has to change all the indexes on the temp array

A slightly less wasteful pattern would be to use users.filter(function() { ... } )[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneikerView Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow
Solution 2 - JavascriptJuan MendesView Answer on Stackoverflow