DEV Community

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

Posted on

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
 
ghost profile image
Ghost •

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...