Joe
Joe

Reputation: 191

Accumulator not initialized when using reduce.call

Why doesn't my accumulator get initialized? I keep getting undefined.

var S = "SOSSTSROS";

var radiatedLetters = Array.prototype.reduce.call(S,function(acc,curr){
    if(!curr.match(/[SO]/)){
        acc++;            
    }
},0);
console.log(radiatedLetters);

Upvotes: 0

Views: 142

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

You need to return the accumulated value from the reducer function, not mutate it:

var S = "SOSSTSROS";

var radiatedLetters = Array.prototype.reduce.call(S, function(acc, curr) {
  if (!curr.match(/[SO]/)) {
    return acc + 1;
  } else {
    return acc;
  }
}, 0);
console.log(radiatedLetters);

Upvotes: 1

Related Questions