user3067952
user3067952

Reputation: 13

rewriting reduce method with a function

Im trying to rewrite the reduce method with this function. It seems like I'm half way there except it only subtracts the last element in the array from the initialValue(10) how can I make all of the numbers subtract from initialValue?

reduce([1, 2, 3], function(total, number) {
  return total - number;
}, 10); // should return 4

function reduce(array,callback,initialValue){
  var sum;
  for(var i = 0; i < array.length; i++){
    sum = callback(initialValue,array[i])
  }
 return sum
}  

Upvotes: 1

Views: 1251

Answers (3)

georg
georg

Reputation: 214949

initial value might be missing, the more accurate version would be like this:

reduce = function(ary, callback, init) {
    var i = 0;
    if (arguments.length < 3)
        init = ary[i++];
    for (; i < ary.length; i++)
        init = callback(init, ary[i], i);
    return init;
}

For the version which is 100% conformant to the specs, see the Mozilla shim

Upvotes: 1

megawac
megawac

Reputation: 11353

You have to call the callback with the update sum on each step. The easiest way to make the change would probably to set sum=initialValue as below,

reduce([1, 2, 3], function(total, number) {
  return total - number;
}, 10); // should return 4

function reduce(array,callback,initialValue){
  var sum = initialValue;
  for(var i = 0; i < array.length; i++){
    sum = callback(sum,array[i]);
  }
  return sum;
}  

Upvotes: 2

mVChr
mVChr

Reputation: 50177

You keep passing in initialValue to the callback. Instead set sum to initialValue initially and pass that in to the callback.

Upvotes: 0

Related Questions