Search code examples
javascriptarraysreturnhigher-order-functions

Returning an array from a higher order function


function map(arr, fn){
for(var i = 0; i <arr.length; i++){
    fn(arr[i]);
    //some code here
    }
}

map([1,2,3,4], function(val){
    return console.log(val * 2);
});

I am having trouble trying to get the result into an array form. For example, [2,4,6,8]. I feel like I know how to do it but I'm blanking out.


Solution

  • The callback (fn) should mutate the array value at hand and map should return the array. See the snippet. Furthermore: just use the native Array.map method I'd say (see mdn for that)

    function map(arr, fn){
      for(var i = 0; i <arr.length; i++){
        arr[i] = fn(arr[i]);
      }
      return arr;
    }
    
    console.log(
      map([1,2,3,4], function(val){  return val*2; })
    );
    
    // but hey, who needs it
    console.log([1,2,3,4].map(v => v*2));