Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6]
let array2 = [3,3,3]

let result = dotProduct(array1,array2) // should return 36

Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries?

Answer №1

dotProduct = (vector1, vector2) => vector1.map((element, index) => vector1[index] * vector2[index]).reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(dotProduct([1,2,3], [1,0,1]));

In this code snippet, we are utilizing Array.prototype.map to generate a new array with multiplied values at each index and Array.prototype.reduce to calculate the sum of the resulting array.

Answer №2

Analysis of Performance (median time in milliseconds based on a thousand runs):

let methods=[
  // (0.65) similar to kyun's solution but without extra variable
  'v.reduce((l,r,i)=>l+r*w[i],0)',

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

  // (0.71) utilizing external length declaration
  'let s2=0,l2=v.length;for(let i2=0;i2<l2;i2++)s2+=v[i2]*w[i2]',

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

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

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

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

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

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

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

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

for(let method of methods){
  let startTime=process.hrtime.bigint()
  eval(method)
  let endTime=process.hrtime.bigint()
  console.log(endTime-startTime+'\t'+method)
}

To mitigate optimization impacts from running identical code repeatedly, I executed the benchmark as

for i in {0..999};do node script.js;done
rather than within the same script.

Answer №3

Looking for a straightforward solution to this issue? Check out this method!

function calculateProduct(array1, array2) {
  let product = 0;
  for (let index = 0; index < array1.length; index++) {
    product += array1[index] * array2[index];
  }
  return product;
}

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

Answer №4

let x = [4,6,8]
let y = [3,0,2]

let z = dotProduct(x,y) // equals 32
console.log(z);
function dotProduct(x,y){
  let result = x.reduce((sum, current, index)=>{
    sum += (current * y[index]);
    return sum;
  }, 0);
  return result;
}

Answer №5

Consider attempting this:

calculate.dotProduct(a, b)

For more information, refer to the documentation here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to integrating animations into a React JS array sorting program

I am currently working on a project that utilizes react js to visually sort an array. I have successfully implemented the sorting algorithm, and the website now displays the correctly sorted array. However, I would like to incorporate an animation to show ...

Accessing the parent div in an Ajax success function

I am looking for a solution to hide a parent div when a link is clicked and an ajax call is successfully made. I have tried placing the hide() function within the success part of the ajax call, but it seems to not work: $('.mylink').click(functi ...

Utilizing a Firebase function with Angular

I created the following function: retrieveLikedProperties(): AngularFirestoreCollection<any> { return this.afs.collection('users', ref => ref.where('uid', '==', this._auth.currentUserId) .where(&a ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Issue with div element not stretching to 100% width

I am currently working on a fluid layout design where the template includes a header, menu, and body section. <div class="w100 h100"> <div id="headerBox" style="height: 10%;" class="w100"> <div style="width: 80%;" class="lfloat ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Using jQuery to eliminate accepting input from form field

Looking to switch between a URL input and file input based on user selection of a radio button. Encountering an issue when attempting to remove the accept attribute from the input, resulting in an Uncaught TypeError: $(...).get(...).removeAttr is not a fu ...

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Resetting the selected options in AngularJS dropdown lists

Utilizing ng-repeat in my HTML code to iterate over a JavaScript array and displaying it within a selection. I am trying to achieve the functionality of clearing all selected data from these dropdown lists when a button is clicked. Snippet of HTML: <d ...

Choose Your Preferences When the Page Loads

I have a dropdown menu where I can select multiple options at once without checkboxes. When the page loads, I want all of the options to be pre-selected by default. I am aware that I can use $(document).ready() to trigger actions after the page has load ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML an ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Identifying the category of a value through a conditional check on another value

I am looking for my code editor to automatically determine the type of extraData based on the value of error, which is being narrowed down by an if statement: export enum ErrorCodes { Unknown = 'UNKWN', BadRequest = 'BDREQ', } int ...

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

Updating the functionality of one-page scrolling - changing to overlap instead of sliding upwards

Hello, I am currently utilizing a JavaScript library to create a website with full page scrolling. If you want to know about the library, check out this link: For those interested, here is an example of my work on jsfiddle: http://jsfiddle.net/aLjLjxux/ ...