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 ;)
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;
})
An ES6 approach in two lines.
const sum = (arr) => arr.reduce((p, c) => +p + +c);
let out = myArr.map(el => sum([...el]));
result=myArr.map(x=>eval([...x].join('+')))