DEV Community

Discussion on: Are one-liners always the best solutions?

Collapse
 
harrisgca profile image
Glenn Harris • Edited

Thanks for posting this.

Without getting into filter vs for loop, part of the reason the filter ran so long was because Math.apply is being rerun for every element in the array. It is more performant to run it once and assign the value to a variable and then run the comparison against the variable.

jsben.ch/IOkIn

Collapse
 
aminmansuri profile image
hidden_dude • Edited

Filter is just the wrong tool for the job. Use a reduce() instead.

Map: convert one elements of an array to an array of something else
Filter: create a new array with certain items removed
Reduce: compute something with the elements of an array

In Smalltalk these were called: collect, select/reject, inject:into: (I like those names better).

martinfowler.com/articles/collecti...

Collapse
 
javila35 profile image
Joe Avila

nice catch