Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  29] [ 3]  / answers: 1 / hits: 16099  / 12 Years ago, mon, october 29, 2012, 12:00:00

How to sum such an Array

[ '',
'4490449',
'2478',
'1280990',
'22296892',
'244676',
'1249',
'13089',
'0',
'0',
'0n' ]



If I call something like that ['','4490449', ... , '0n' ].reduce(function(t,s){ return t+s) on that array, the stings are joined and not summed.



I've tried some casting with parseInt() but this results in NaN :)


More From » arrays

 Answers
231

You need to assure that the values you are summing are integers. Here's one possible solution:



var ary=[ '', '4490449', '2478', '1280990', '22296892', 
'244676', '1249', '13089', '0', '0', '0n' ];

console.log(
ary
.map( function(elt){ // assure the value can be converted into an integer
return /^d+$/.test(elt) ? parseInt(elt) : 0;
})
.reduce( function(a,b){ // sum all resulting numbers
return a+b
})
)​;


which prints '28329823' to the console.



See fiddle at http://jsfiddle.net/hF6xv/


[#82289] Saturday, October 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailey

Total Points: 355
Total Questions: 91
Total Answers: 91

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;