Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum up digits together within an Array

Could anyone help me please.

I have created a function and within it I have an array containing string representations of integers.

var a = ['11', '22', '33' ,'44'];

What I am trying to do is to get a sum of individual digits in each element of the array. For example, the element containing '11' would give me 2 (1 + 1), '22' would give me 4 (2 + 2), and so on... So I should get [2,4,6,8] as the final output. How can I do this.

Thank you,

like image 681
John Snow Avatar asked Jan 31 '26 02:01

John Snow


1 Answers

I'm assuming you meant [2,4,6,8] as the output, which would be the sum of the digits of each element in the array you provided:

JsBin Example

var a = ['11', '22', '33' ,'44'];

var b = a.map(function(num) {
  return num.split('').map(Number).reduce(function(a, b) {
    return a + b;
  });
}); 

// b = [2,4,6,8]
like image 108
omarjmh Avatar answered Feb 02 '26 14:02

omarjmh