Dot product of two arrays in Javascript

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

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

What's an efficient way of implementing the dotProduct method without importing any new libraries?

5 Answers

dot = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
console.log(dot([1,2,3], [1,0,1]));

Here we use Array.prototype.map to create a new array with multiplied results of each index and Array.prototype.reduce to sum the values of resulting array.

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

const c = dotProduct(a,b) // will equal 4
console.log(c);
function dotProduct(a,b){
  const result = a.reduce((acc, cur, index)=>{
    acc += (cur * b[index]);
    return acc;
  }, 0);
  return result;
}

Here is a simple way to solve this problem!

function dot_product(vector1, vector2) {
  let result = 0;
  for (let i = 0; i < 3; i++) {
    result += vector1[i] * vector2[i];
  }
  return result;
}

console.log(dot_product([1, 2, 3], [4, 5, 6])) // output: 32

Benchmark (the comments start with the median time of a thousand runs in ms):

let opt=[
  // (0.65) like kyun's answer but without extra variable
  'v.reduce((l,r,i)=>l+r*w[i],0)',

  // (0.66) like kyun's answer
  'v.reduce((l,r,i)=>{l+=(r*w[i]);return l},0)',

  // (0.71) variable for length declared outside block
  'let s2=0,l2=v.length;for(let i2=0;i2<l2;i2++)s2+=v[i2]*w[i2]',

  // (0.72) block-scoped variable for length
  'let s=0;for(let i=0,l=v.length;i<l;i++)s+=v[i]*w[i]',

  // (1.20) like the accepted answer
  'v.map((_,i)=>v[i]*w[i]).reduce((l,r)=>l+r)',

  // (1.93) hardcoded number for length
  'let s1=0;for(let i1=0;i1<1e4;i1++)s1+=v[i1]*w[i1]',

  // (2.05) check length during each iteration
  'let s3=0;for(let i3=0;i3<v.length;i3++)s3+=v[i3]*w[i3]',

  // (6.25) no `let` for sum variable
  's4=0;for(let i4=0,l4=v.length;i4<l4;i4++)s4+=v[i4]*w[i4]',

  // (12.17) no `let`
  's5=0;l5=v.length;for(i5=0;i5<l5;i5++)s5+=v[i5]*w[i5]',

  // (16.36) `var` instead of `let`
  'var s6=0,l6=v.length;for(var i6=0;i6<l6;i6++)s6+=v[i6]*w[i6]'
]

opt.sort(()=>Math.random()-.5)
let v=Array.from({length:1e4},()=>Math.random())
let w=Array.from({length:1e4},()=>Math.random())

for(let opti of opt){
  let t1=process.hrtime.bigint()
  eval(opti)
  let t2=process.hrtime.bigint()
  console.log(t2-t1+'\t'+opti)
}

In order to reduce the impact of optimizations for running the same code multiple times, I ran the benchmark like for i in {0..999};do node script.js;done instead of running each option 1000 times inside the script.

Related