-2

as discribed i would love to get the sum of the Strings in the Array with the reduce function.

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];

const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
  return accumulator.length + currentValue.length;
});

console.log(sumtwo);

So far i tried to get the length of my two parameters but when i console.log it i just get a Nan.

2

2 Answers 2

2

You're returning a number, so you do not need to access the length property of accumulator. Besides that, you'd need to specify an initial value of 0, so JavaScript knows it's a number from the beginning, because by default, it is set to the first value from the array you're trying to reduce (in this case apple).

Your fixed code would look like this.

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];
    
const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.length; // accumulator is already a number, no need to access its length
}, 0); // Initial value of 0
    
console.log(sumtwo);

Sign up to request clarification or add additional context in comments.

Comments

1

I would use the join() array method, then find the length

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];
const sumtwo = fruitsb.join('');

console.log(sumtwo.length);

Comments