简体   繁体   中英

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?

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 ;)

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;
});
var parseString = function(n) { 
    return n.split('')
          .reduce(function(a, b) {
                  return parseInt(a) + parseInt(b);
           })
    };

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

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/

An ES6 approach in two lines.

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM