Implement array map function - Node.js Array

Node.js examples for Array:Array Operation

Description

Implement array map function

Demo Code


Array.prototype.map = function(callback) { 

  
  var obj = this;
  var value, mapped_value;
    A = new Array(obj.length);
 
  for ( var i = 0; i < obj.length; i++ ) {
    value = obj[i];/*  w w w. jav a 2s  . c  o  m*/
    mapped_value = callback.call(null, value); 
    A[i] = mapped_value;
  }
   
    return A;
  };  
  
var arr = [1,2,3];
var new_arr = arr.map(function(value) {
  return value*value;
});

console.log(new_arr);

Related Tutorials