➕ Summing all digits of a number with Array.reduce

const sumDigits = (number) => {
  const digits = [...number.toString(10)].map((digit) => Number(digit));
  return digits.reduce((sum, digit) => sum + digit, 0);
};

console.log(sumDigits(3041)); // 8
console.log(sumDigits(987)); // 24
console.log(sumDigits(10437)); // 15

Here's an easy way of summing all the digits of a given number in JavaScript:

First, we need to get the digits separately, for this we can convert the number to a string of base 10, spread all the characters in an array and map those characters to the equivalent number.

Then, with the help of the reduce method we can compute the sum of the digits. The reduce method iterates over each item of an array and executes the given function with each item as the 2nd argument and an accumulator value as the first one. This accumulator is the returned value of the function on the previous iteration (the first time the default value is used, 0 in our case). Hence, on the first iteration the function will return the first digit, on the second one it will return the sum of the first 2 digits and so on.