Page 1 of 1

Dot product of two arrays in Javascript

Posted: 13 Nov 2020, 12:26
by Marius
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

Dot product of two arrays in Javascript

Posted: 13 Nov 2020, 14:15
by Admin
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