+ 1
Array multiplication?
Say we have an array of numbers. These numbers can be anything and as many numbers as you want. Is there a way to multiply all of the numbers in the array by each other in pure JS? Like This: array = [5, 4, 2, 2] 5*4*2*2=80
7 Answers
+ 2
Kishalaya Saha That's exactly what I'm trying to learn about. Lol. Thanks!
+ 2
console.log( [5,4,2,2].reduce((m,a)=>m*a) );
https://code.sololearn.com/WYsgPI3qBqtj/?ref=app
+ 1
Sure, all we need is a for loop!
var len = array.length;
var prod = 1;
for (var i = 0; i < len; i++) {
prod *= array[i];
}
Now the variable prod stores the result of multiplying all the numbers in your array.
If you're not familiar with for loops, this code may look quite confusing. Keep going through the lesson on Sololearn, and you'll learn about them in no time!
+ 1
let array = [5, 4, 2, 2];
let reducer = (accumulator, elem) => accumulator * elem;
let product = array.reduce(reducer);
+ 1
Daniel Cooper It's awesome that you came up with this question right before the lesson! đ
+ 1
Kishalaya Saha Actually, I've completed the lesson. I've competed the entire JS course. I just didn't focus on for loops because of reasons I don't remember. Lol
+ 1
That happens with me all the time. I don't remember a lesson unless I use the content myself đ