I'd like to know the fastest and most efficient way to multiply array elements together using javascript.
var array = ["1", "2", "3", "4"];
So the outcome would total 10.
I'd like to know the fastest and most efficient way to multiply array elements together using javascript.
var array = ["1", "2", "3", "4"];
So the outcome would total 10.
First, those values are strings, not numbers, so the first thing to do is make them numbers:
array.map(Number)
Then multiply with .reduce
array.map(Number).reduce(function(product, value) { return product * value; });
edit — a comment wisely notes that the *
operator will try to convert its operands to numbers anyway. With the explicit conversion to numbers, you could add a filter to see if there were any NaN
values produced, but NaN
spreads like cancer so it really wouldn't matter. Consider the numeric conversion optional.
Now, in general, if I were getting an array of numbers-as-strings from an API, I'd be inclined to do an explicit conversion, because in a sense that means that there's really something wrong with the design of the API. I'd prefer to isolate any "interesting" code from weird stuff like that.
The most efficient/performant way will be always to use regular loop:
var array = ['1', '2', '3', '4'], i = array.length, result = 1;
while (i > 0)
result *= array[--i];
But since that kind of performance will never matter in the real world, I suggest you to use reduce
:
var array = ['1', '2', '3', '4'];
var result = array.reduce(function(a, b) {
return a * b;
});
console.log(result);
The fastest form of loop is standard for
, See map vs for-loop performance test.
NOTE : The slower is map() function like you can see in test.
var Array = ["1", "2", "3", "4"];
var total=1;
for (var i = 0; i < Array.length; ++i) {
total *= Array[i];
}
alert(total);
Hope this helps.
Fast and efficient, go with a good old for loop, see http://jsperf.com/reduce-v-for-javascript
You can use reduce
var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
with arrow functions in ES6, it is even simpler.
sum = array.reduce((pv, cv) => pv+cv, 0);
or with for loop
var total = 0;
for (var i = 0, n = array.length; i < n; ++i){
total += array[i];
}
and with crazy way
var a = [1,2,3,4,5];
sum = eval(a.join("+"));