How to add numbers together like 2020 = 2 + 0 + 2 + 0?

  • 0
    I have an input, I enter 2020 into it, how can I make it turn out 2 + 0 + 2 + 0?
    Or how do I split it into 2,0,2,0?
    JavaScript Anonymous, Jun 24, 2020

  • 2 Answers
  • 0
    If the input contains only positive numbers, then this is possible:

    '2020'.split('').reduce((a, b) => parseInt(a) + parseInt(b)); // 4
    Anonymous

  • 0
    input.split('').map(v=>parseInt(v)).reduce((s,v)=>s+v,0)
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!