nkr15
nkr15

Reputation: 149

Adding digits in an array with JavaScript

var myArr = [ '111' , '222' , '333' ] ;

I would like this to become [3, 6, 9] essentially summing up the digits. Would a nested for-loop or map be the best route to achieve this?

Upvotes: 0

Views: 127

Answers (5)

Andy
Andy

Reputation: 63525

An ES6 approach in two lines.

const sum = (arr) => arr.reduce((p, c) => +p + +c);
let out = myArr.map(el => sum([...el]));

DEMO

Upvotes: 0

Jason
Jason

Reputation: 118

I think this fiddle gives you the result you are after:

var myArr = [ "111" , "222" , "333" ] ;
var newArr = myArr.map(function(string){
    var chars = string.split("")
  var value = 0;
  for(var i = 0; i < chars.length; i++ ){
    value = value + parseInt(chars[i])
  }
  return value;
})

https://jsfiddle.net/bw7s6yey/

Upvotes: 0

George Chen
George Chen

Reputation: 6939

var parseString = function(n) { 
    return n.split('')
          .reduce(function(a, b) {
                  return parseInt(a) + parseInt(b);
           })
    };

myArr.map(function(str) {return   parseString(str)})

Upvotes: 0

user4227915
user4227915

Reputation:

You can map and evaluate the sum reducing the regex matches for each digit:

var myArr = [ '111' , '222' , '333' ];

var result = myArr.map(function(text){
    return text.match(/\d/g).reduce(function(x, y){
        return +y + x;
    }, 0);
});

O.innerHTML = JSON.stringify(result);
<pre id=O>

Hope it helps ;)

Upvotes: 2

DarkAjax
DarkAjax

Reputation: 16223

I'd maybe do something like this:

myArr.map(function(a){
    var temp = 0;
    a.split('').forEach(function(b){
        temp += parseInt(b,10);
    });
    return temp;
});

Upvotes: 2

Related Questions