Multiplying array elements with Javascript -


i'd know fastest , efficient way multiply array elements using javascript.

var array = ["1", "2", "3", "4"]; 

so outcome total 10.

first, values strings, not numbers, first thing make them numbers:

 array.map(number) 

then multiply .reduce

 array.map(number).reduce(function(product, value) { return product * value; }); 

edit — comment wisely notes * operator try convert operands numbers anyway. explicit conversion numbers, add filter see if there nan values produced, nan spreads cancer wouldn't matter. consider numeric conversion optional.

now, in general, if getting array of numbers-as-strings api, i'd inclined explicit conversion, because in sense means there's wrong design of api. i'd prefer isolate "interesting" code weird stuff that.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -