Javascript Array map(f)

Description

Javascript Array map(f)


Array.prototype.map = function(f) {
  var result = [];
  
  for (var i=0; i<this.length; i++){
    result.push(f(this[i]));//w ww .j  a  v a2s  .c  o  m
  }
  return result;
}

Javascript Array map(f)

//Assume there is no map method exist for Array.
//Implementing Array.map() method

Array.prototype.map = function(f){
  var newArray = [];
  var i;//from  ww  w.j a v  a 2  s  .c  o m
  //Traversing the array
  //this refers to the array instance
  
  for( i = 0; i<this.length; i++){
    newArray.push(f(this[i],i,this));
  }
  
  return newArray;
}

Javascript Array map(f)

console.log("hola");

var map = (list, f) => {
    return list.reduce(f);
};

Array.prototype.map_ = function (f){
    return this.reduce(function (acc, current){
        return acc.concat(f(current));
    }, []);//from   w  w w  .  j  a v  a  2 s  . co  m
}


Array.prototype.map_2 = f => {
    return this.reduce((acc,current) => {
        return acc.concat(f(current))
    },[]
    )
};


var sumar = (x,y) => {x+y};

var nume = [1,3,4,5,4,5,6,78,8,8,88,88,8,8,8,8,8,8,8,8,8,8,8,8,8,8,888,8,8,8,8,8,8,8,8,8,8]

console.log(nume.map_2(a => a * 10));

Javascript Array map(f)

Array.prototype.map = function(f) {
    var ret = [];
    for (var i = 0; i < this.length; i++) {
        var val = this[i];
        var newVal = f(val);
        ret.push(newVal);/*w w  w . jav a  2 s .c  o  m*/
    }
    return ret;
};

function f(x) { return x * 2; }
function g(x) { return x + 3; }
function h(x) { return f(g(x)); }

var numbers = [ 1, 2, 3 ];

console.log('numbers.map(f):', numbers.map(f)); // [ 2, 4, 6 ]
console.log('numbers.map(g):', numbers.map(g)); // [ 4, 5, 6 ]
console.log('numbers.map(g).map(f):', numbers.map(g).map(f)); // [ 8, 10, 12 ]
console.log('numbers.map(h):', numbers.map(h)); // [ 8, 10, 12 ]



PreviousNext

Related