-3

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.

  • 1
    I downvoted because you would find the problem using your debugger. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – jabaa Dec 05 '22 at 18:37
  • https://stackoverflow.com/questions/39698450/calling-reduce-to-sum-array-of-objects-returns-nan – epascarello Dec 05 '22 at 18:38

2 Answers2

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);
tobimori
  • 527
  • 2
  • 12
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);
Sarah
  • 354
  • 1
  • 12