user4901852
user4901852

Reputation:

Type error related to accumulator of reduce method

Im trying to figure out why the following code

const test = function(arr){
    const reducer = (acc,el) => {
        if(el>0){
            return acc.push(el**2);
        }
    }
    return arr.reduce(reducer,[]);
}
console.log(test([2,3,4-5-6-1]));

throw a type error saying that acc.push is not a function. It seems that I need to declare in some way that the parameter acc is supposed to be an array but I dont know how.

Maybe this is a newbie question but I dont know what to do. Can someone enlighten me about this error?

Upvotes: 0

Views: 130

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Array.push returns the new length of the array. You need to return the array from the reducer.

const test = function(arr){
    const reducer = (acc,el) => {
        if(el>0){
            acc.push(el**2);
        }
        return acc;

    }
    return arr.reduce(reducer,[]);
}
console.log(test([2,3,4-5-6-1]));

However, there'a simpler way: filter and map

console.log(
    [2, 3, -1]
        .filter(x => x > 0)
        .map(x => x ** 2)
);

Upvotes: 1

hgb123
hgb123

Reputation: 14891

The accumulator must be returned on every iteration. Array.prototype.push() return new length of the array so that on the next iteration, it produces error

const test = function (arr) {
  const reducer = (acc, el) => {
    if (el > 0) {
      acc.push(el ** 2)
    }
    return acc
  }

  return arr.reduce(reducer, [])
}
console.log(test([2, 3, 4, 5, 6, 1]))

Upvotes: 1

Related Questions