JavaScript Array Map and Reduce Methods

The map() method creates a new array with the results of calling a provided function on every element in this array.

Array.prototype.map = function (fn) {
  var l = this.length;
  var a = [];
  for (var i = 0; i < l; i++) {
    a.push(fn(this[i]));  
  }
  return a;
};

Download this code snippet at GitHubGist JavaScriptArray#map. More info at  MDN Array#map.


The reduce() method applies a function against an accumulator and each value of the array has to reduce it to a single value.

Array.prototype.reduce = function (fn, init) {  
  var s = init;
  var l = this.length;
  for (var i = 0; i < l; i++) {		
    s = fn(s, this[i]);
  }
  return s;
};

Download this code snippet at GitHubGist JavaScriptArray#reduce.  More info at  MDN Array#reduce.