dhairyashah
Portfolio

Mar 31st, 2023

How to multiply two arrays in Javascript

Author Picture

Dhairya Shah

Software Engineer

Although multiplying two arrays in Javascript is a straightforward task, many people struggle with the concept and may find it challenging to achieve.

The question of whether arrays can be multiplied in Javascript has been raised in multiple forums and discussions. The answer is affirmative - arrays can indeed be multiplied in Javascript.

As a result in this article, I will show you a simple method for how to multiply two arrays in Javascript. This is a common operation in linear algebra and vectors, and it can be useful for various applications.

One way to do this is to use the for loop to iterate over the elements of the arrays and multiply by their corresponding indices. Then we push it to the product array. For example,

const arr1 = [1,2,3,4,5]
const arr2 = [5,4,3,2,1]
const product = [];

for(let i = 0; i < arr1.length; i++){
    product.push(arr1[i] * arr2[i]);
}

console.log(product) // [5,8,9,8,5]

Here, we have got a whole new array of products of arr1 and arr2.

Conclusion

In conclusion, multiplying two arrays in Javascript is possible and can be achieved through the use of a for loop to iterate over the elements of the arrays and multiply them by their corresponding indices.

This process can be useful for various applications, particularly in linear algebra and vectors. With the simple method outlined in this article, anyone can successfully multiply two arrays in Javascript.

I hope you have enjoyed reading the article. Thanks for reading!