Implement map in javascript
Projecting Arrays
Applying a value to a function and getting a new value is called a projection. To project (transform) one array to another, we have to process each element in the array and collect the results in a new array.
- We will be solving a problem using
Array.prototype.forEach()
. - We will define
Array.prototype.map()
usingArray.prototype.forEach()
. - We will solve the same problem using
Array.prototype.map()
This post is a follow up post of the
- Getting started Functional Programming in JavaScript. I would recommend reading that post first.
Problem
Project an array of videos into an array of {id, title} pairs using Array.prototype.forEach()
Let's solve with
Array.prototype.forEach()
Do notice that the array projections have two operations in common:
- Traversing the source array
- Adding each item's projected value to a new array
We can abstract these common operations in Array.prototype.map()
Implement
Array.prototype.map()
usingArray.prototype.forEach()
Lets solve with
Array.prtotype.map()
Key Learnings
- Projection methods iterates over array and creates a new array of projected array element
Array.prototype.map()
allows you to specify the projection.