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

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Tips for saving the web address and breaking down each word

Hello, I am familiar with how to store URL parameters using the following JavaScript code. However, I am wondering if there is a way to store each word that comes after a slash in a URL. For example, let's consider the URL: http://localhost:9000/Data ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...

Error: Unexpected identifier in jQuery ajax line

I'm currently encountering an issue with my jQuery ajax call that's throwing an "Uncaught SyntaxError: Unexpected identifier" error at line 3. For confidentiality reasons, I have omitted the original URL. However, even after removing the csrHost ...

A Step-by-Step Guide to Launching PDF Blob from AJAX Response in a Fresh Chrome Tab

I'm sending a POST request to a server, and in response, I receive a PDF file that is returned as a blob. To handle this blob, I am using the "handle-as='blob'" attribute of iron-ajax (a Polymer element), just to cover all bases. Now, my g ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Comparing and highlighting words in strings using JavaScript

Seeking assistance with comparing and styling words as shown in the image below: https://i.stack.imgur.com/Ffdml.png I attempted using JavaScript for this task but have not been successful so far. <div class="form-group"> <div class="col-md ...

Strategies for retaining additional fields added via JavaScript when the page is refreshed

var newField = document.createElement("lastExp"); newField.innerHTML = 'insert new form field HTML code here'; document.getElementById("lastExp").appendChild(newField); I have a button that adds an additional form field with a simple click. ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...

What sets declaring variables apart in Vue?

Can you clarify the distinctions among various methods of declaring variables? When should I employ each of these declaration methods? <script> const someVariable = 12345 export default { name: 'App', } </script> <script> e ...

Retrieve XML node through AJAX request

I am in need of using AJAX to retrieve values from XML nodes and then utilize those values within an existing JavaScript function. Here's a sample of the XML data: <cars> <car mfgdate="1 Jan 15" name="Ford" id="1"> <engine litre ...

Identify HTML elements within a textarea or text input using JavaScript while also accommodating the common special characters ">" and "<"

Is there a way to accurately detect HTML tags in textarea or text input fields before submitting a form? While it may seem straightforward to use regular expressions like /<\/?[^>]*>/gi.test(str) for this purpose, the challenge arises when de ...

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

JavaScript makes it easy to streamline conditions

Can someone help me simplify this repetitive condition? if (this.get('fileUrl')) { const isUnsplash = this.get('fileContainer.asset_kind') === 'UnsplashAsset'; return Asset.create({ url: this.get('f ...