I couldn\'t find an example here what I\'m really looking for. I\'d like to multiply all array elements, so if an array contains [1,2,3] the sum would be 1*2*3=6; So far I\'
The reduce() method executes a provided function for each value of the array and reduces the array to a single value
const arr = [1,2,3];
const sum = arr.reduce((prevValue,curValue) => {
return prevValue * curValue
},1);
console.log(sum);
prevValue is the initial value and it's equal 1 in this example
curValue is the value of the current element in array
If you want to multiply some consecutive numbers like 1,2,3 then, then apply this code and enter the number in the console (arr)
let array = [];
function factorisation(arr) {
for (let j = arr; j > 0; j--) {
array.push(j);
}
return multiply();
}
function multiply() {
var sum = 1;
for (var i = 0; i < array.length; i++) {
sum = sum * array[i];
}
return sum;
}
console.log(factorisation(5));
//5*4*3*2*1 = 120
The cause is already known. Here's an alternative - using Array.reduce for your method:
console.log( [1, 2, 3].reduce( (a, b) => a * b ) );
console.log( Array.from( {length: 20} )
.map( (v, i) => i + 1 )
.reduce( (a,b) => a * b )
.toLocaleString());
// for empty arrays, use some initial value
const arr = [];
if (arr.reduce( (a, b) => a * b, -1 ) === -1) {
console.error(`The given array ${arr} is empty`);
}
See also
You need to have () when you call the function.
Like multiply([1,2,3])
Demo here
You're not calling multiply as a function:
multiply([1,2,3]);
The alternative way to use Array.reduce should have the initial value set to 1 or else our function will return 0 no matter what.
[1, 2, 3].reduce((a, b)=> a*b, 1)
per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce