Suppose we have two arrays of different lengths:
let array1 = [22, 42, 28, 100, 28, 48, 38, 48, 26, 32, 58, 36, 28, 42, 42, 38, 28, 28, 38, 24, 32, 38, 38, 28, 46, 38, 42, 46, 32, 46, 38, 48, 9, 6, 5, 8, 5, 56, 24, 32, 5, 46];
let array2 = [25, 50, 75, 100, 150, 250];
It’s necessary multiplication be performed in this way:
22×25, 22×50, 22×75 … 42×25, 42×50 …
How to do this correctly?
4
Answers
You can use
Array::reduce()
andArray::map()
to collect the values:Here you can do one thing…
Get ready to dive into the exciting world of JavaScript! We’re going to multiply each element of one array by each element of another, using nested loops. Here’s a handy code snippet to get you started:
In this thrilling piece of code:
We’ve got our arrays
array1
andarray2
all set up.We create a shiny new empty
resultArray
where we’ll store our multiplication results.Our nested loops are at work here: the outer loop takes a tour through
array1
, while the inner loop exploresarray2
.Inside these loops is where the magic happens: we multiply elements from both arrays and push the results into our
resultArray
.And voila! We log
resultArray
to reveal all those multiplied values.-NAMASTE(0_0)
You could map the products.