0
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?

2
  • OP, while you have a number of answers here, for future reference it's important that you attempt the solution yourself and if you run into problems post that as your question so we can see what you've tried, rather than using SO as a coding service. Commented Apr 9, 2016 at 1:03
  • Also funny: result=myArr.map(x=>eval([...x].join('+'))) Commented Apr 9, 2016 at 9:04

5 Answers 5

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

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

1 Comment

Do make sure you add an explanation to help people better understand your answer, rather than just leaving a chunk of code.
0

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/

Comments

0

An ES6 approach in two lines.

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

DEMO

1 Comment

ES6 allows you to use [...el] instead of el.split('')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.