This content originally appeared on 2ality – JavaScript and more and was authored by Dr. Axel Rauschmayer
In this blog post, we look at three ways of processing Arrays:
- The
for-of
loop - The Array method
.reduce()
- The Array method
.flatMap()
The goal is to help you choose between these features whenever you need to process Arrays. In case you don’t know .reduce()
and .flatMap()
yet, they will both be explained to you.
In order to get a better feeling for how these three features work, we use each of them to implement the following functionality:
- Filtering an input Array to produce an output Array
- Mapping each input Array element to one output Array element
- Expanding each input Array element to zero or more output Array elements
- Filter-mapping (filtering and mapping in one step)
- Computing a summary for an Array
- Finding an Array element
- Checking a condition for all Array elements
Everything we do is non-destructive: The input Array is never changed. If the output is an Array, it is always freshly created.
This content originally appeared on 2ality – JavaScript and more and was authored by Dr. Axel Rauschmayer
Dr. Axel Rauschmayer | Sciencx (2022-05-26T00:00:00+00:00) Processing Arrays non-destructively: for-of
vs. .reduce()
vs. .flatMap()
. Retrieved from https://www.scien.cx/2022/05/26/processing-arrays-non-destructively-for-of-vs-reduce-vs-flatmap/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.