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,
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With