DEV Community

Cover image for Implementation of ES6 Map() function
Prashant Andani
Prashant Andani

Posted on

4 1

Implementation of ES6 Map() function

//implementing map function

/* Implemetation */
const arrayMap = (arr, fn) => {
  const arrTemp = [];
  for (var i = 0; i < arr.length; i++) {
    arrTemp.push(fn(arr[i], i));
  }
  return arrTemp;
};

/* Usage */
// const arr = [1,2, 3];
// const iterator = each => each + 1;
const result = arrayMap(arr, iterator);
//console.log(result);

Top comments (5)

Collapse
 
drmandible profile image
DrMandible

Short and sweet but I think you forgot: var arrayMap = new Map();

Collapse
 
prashantandani profile image
Prashant Andani

Thanks!
The idea here is to implement a Map() alternative. Just to understand how it can be implemented.

Collapse
 
drmandible profile image
DrMandible

Ohhh I see now. That makes more sense. Thanks for clarifying!

I know it's a tough balance to make a post concise while still being clear enough to a wide range of audiences. I'm still learning but probably a more seasoned dev knew what you were doing.

Collapse
 
mateiadrielrafael profile image
Matei Adriel

The map function needs to get the current value, index and array. Also, why that var? Tha can become a const

Collapse
 
prashantandani profile image
Prashant Andani • Edited

Updated... Thanks for pointing that out... 'Const' should do and also I missed index.

Map will pass the current value to the callback function which in this case is 'fn', which has 'currentValue' and 'index' as a parameter...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay