DEV Community

Cover image for polyfill: Array.Map()
Naveen Kumar Chintakindi
Naveen Kumar Chintakindi

Posted on

polyfill: Array.Map()

const original_Arr=[1,2,3];

Array.prototype.myMap=function(cb){
  let argArr=this; 
  let output_Arr=[];
  for(let i=0;i<argArr.length;i++){
    const value=cb(argArr[i],i,argArr);
    output_Arr.push(value);
  }
  return output_Arr;
}

const new_Arr=original_Arr.myMap((element,index,arr)=>{
  return element*2;
});

console.log(newArr); //[2,4,6]
Enter fullscreen mode Exit fullscreen mode
  • In the above method we used array prototype(i.e., Array.prototype.myMap()) to create a custom Array.map() method.

  • As shown above this refer to the actual array on which we are running the myMap(). Here, this refers to original_Arr[].

Top comments (0)