+ 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

23rd Sep 2018, 1:55 AM
Daniel Cooper
Daniel Cooper - avatar
7 Respuestas
+ 2
Kishalaya Saha That's exactly what I'm trying to learn about. Lol. Thanks!
23rd Sep 2018, 2:49 AM
Daniel Cooper
Daniel Cooper - avatar
+ 2
console.log( [5,4,2,2].reduce((m,a)=>m*a) ); https://code.sololearn.com/WYsgPI3qBqtj/?ref=app
23rd Sep 2018, 5:20 AM
Calviղ
Calviղ - avatar
+ 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!
23rd Sep 2018, 2:11 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
let array = [5, 4, 2, 2]; let reducer = (accumulator, elem) => accumulator * elem; let product = array.reduce(reducer);
23rd Sep 2018, 2:24 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 1
Daniel Cooper It's awesome that you came up with this question right before the lesson! 😊
23rd Sep 2018, 2:54 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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
23rd Sep 2018, 3:31 AM
Daniel Cooper
Daniel Cooper - avatar
+ 1
That happens with me all the time. I don't remember a lesson unless I use the content myself 😂
23rd Sep 2018, 4:05 AM
Kishalaya Saha
Kishalaya Saha - avatar