John Snow
John Snow

Reputation: 71

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,

Upvotes: 3

Views: 112

Answers (6)

Andy
Andy

Reputation: 63540

map over the array, split each element, convert it to a number then add them, and return the final array.

function thing(arr) {
  return arr.map(function (el) {
    return el.split('').map(Number).reduce(function (p, c) {
      return p + c;
    });
  });
}

thing(arr) // [ 2, 4, 6, 8 ]

Or something more DRY with ES6:

const add = (a, b) => a + b;

function sumElements(arr) {
  return arr.map(el => [...el].map(Number).reduce(add));
}

DEMO

Upvotes: 2

StackSlave
StackSlave

Reputation: 10627

This should work on all Browsers:

function wack(a){
  var r = [];
  for(var i=0,l=a.length; i<l; i++){
    var s = a[i].split(''), t = 0;
    for(var n=0,c=s.length; n<c; n++){
      t += +s[n];
    }
    r.push(t);
  }
  return r;
}
var test = ['11', '22', '33', '44', '111'];
console.log(wack(test));

Upvotes: 1

isvforall
isvforall

Reputation: 8926

One liner with ES6

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

var result = a.map(e => e.split('').reduce((p, c) => +p + +c))

console.log(result); //[ 2, 4, 6, 8 ]

Upvotes: 1

Yuriy Yakym
Yuriy Yakym

Reputation: 3921

Another approach using mathematics:

var a = ['11', '22', '33' ,'44'];
var res = a.map(Number).map(function(digit) {
   var result = 0;
   while(digit) {
      result += digit % 10;
      digit = Math.floor(digit/10);
   }
   return result;
});

document.write(res);

Upvotes: 1

omarjmh
omarjmh

Reputation: 13896

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]

Upvotes: 3

Leeish
Leeish

Reputation: 5213

I'm not sure this is what you are asking, but I'll give it a go.

var a = [11,22,33,44];
var b = [];
for(i in a){
    b.push(a[i]*2);
}
//b == [22,44,66,88]

Your array is strings so you might want to wrap a[i] in the Number() function.

Upvotes: 0

Related Questions