-1

I am trying to solve this function challenge and get the requested output. I tried to come up with a solution but this is beyond my me. Please help me understand this so I can solve this challenge,

I researched using an array but I don't know how to separate the elements(integers) so I can add them.

function getSumOfDigits(num) {

     return num + num;
}
/* Do not modify code below this line */

console.log(getSumOfDigits(42), '<-- should be 6');
console.log(getSumOfDigits(103), '<-- should be 4');

I am not getting an error message but the input is returning the wrong output.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What is the problem in the challenge? – Barmar Aug 28 '19 at 19:31
  • I think this site is not for home works. You need split your all number and sum that array – Gabriel Martinez Bustos Aug 28 '19 at 19:34
  • Things to look up: [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), the [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) constructor, and [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). – Scott Sauyet Aug 28 '19 at 19:35

1 Answers1

0

EDIT: To add explanation for the answer and include a solution provided on the comment line.

You can convert the number into string so you can be able to manipulate each digit inside the number. To perform arithmetic operation on the digits, you will need to convert the characters back to numbers.

function getSumOfDigits(num) {
  let str = num.toString();
  let sum = 0;
  for(value of str)
    sum += Number(value);

  return sum;
}

For future reference I have included the elegant solution provided on the comment line below (credit to @Scott Sauyet):

getSumOfDigits = (nbr) => String(nbr).split('').map(Number).reduce((a, b) => a + b, 0);

In both cases you can call the function like:

console.log(getSumOfDigits(42));
console.log(getSumOfDigits(103));

The link provided on the question above has a lot more solutions to this problem.

Addis
  • 2,480
  • 2
  • 13
  • 21