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
Post a Comment