Dot product of two arrays in Javascript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Dot product of two arrays in Javascript

What's an efficient way of implementing the dotProduct method (to get the Dot product [or scalar product] of two arrays) without importing any new Javascript libraries?
For example:

Code: Select all

const a = [1,2,3]
const b = [1,0,1]

const c = dotProduct(a,b) // will equal 4

Admin Posts:805
Here is a method.
Use the map() function to create a new array with multiplied results of each index and the reduce() function to sum the values of resulting array.

Code: Select all

var dot = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);

const a = [1,2,3]
const b = [1,0,1]

console.log(dot(a, b));  // 4

Similar Topics