Calculating the Product of Two Arrays

I'm attempting to multiply two arrays that are the same length and generate a third array from it.

After experimenting with loops, I believe using a nested loop is the most effective approach.

Here is my initial implementation, which unfortunately multiplied out the entire array:

var one = [1, 2, 3, 4, 5];
var two = [1, 2, 3, 4, 5];

//var partOne = one.length

var partOne = []
  for(var i=0; i<one.length;i++) {
    for(var j=0;j<two.length;j++) {
      partOne.push({value:one[i] * two[i]});
    }
  }

I am aiming for something akin to this example below:

var a = [3, 5]
var b = [5, 5]

//answer

var c = [15, 25]

Answer №1

function multiplyNumbers(arr1, arr2) {
    var result = [];
    for (var i=0; i<arr1.length;i++) {
        result.push(arr1[i]*arr2[i]);
    }
    return result;
}
var array1 = [3, 5 ];
var array2 = [5, 5 ];
var multipliedArray = multiplyNumbers(array1, array2);
console.log(multipliedArray);

var array1 = [3, 5 ]
var array2 = [5, 5 ]
var multipliedArray = []

for (var i=0; i<array1.length;i++) {
    multipliedArray.push(array1[i]*array2[i]);
}

console.log(multipliedArray);

Answer №2

const numbers = [3, 5];
const multipliers = [5, 5];

// Multiply each element in 'numbers' array by the corresponding element in 'multipliers' array
const result = numbers.map((num, index) => { return num * multipliers[index]; });

Output:

// Returns: [ 15, 25 ]

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

Extract data from an API endpoint using JavaScript or React

I have the primary website link, which necessitates an authorization header for access every time. //console.log contains this information - accounts:[{categoryId:"some info"... }] api/v2/accounts To extract accountId and categoryId from the i ...

In one application, there are two connections established with mongoose. The purpose of the second connection is to establish a dependency on the

Seeking advice: I am facing an issue where I need to establish two separate connections to the database. The first database contains login information, while the second holds all other relevant data. Can this be achieved through integration of Node.js, m ...

How can I use jQuery to display a div alongside the element that is currently being hovered over?

Imagine having multiple divs similar to these: UPDATE: <div class="ProfilePic"> <a href="#"> <img src="lib/css/img/profile_pic1.png" alt="" class="ProfilePicImg"/> </a> <div class="PopupBox" style="display: ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Tips for determining the duration between the Monday of last week and the Sunday of last week

Can anyone help me figure out how to retrieve the dates from last week's Monday to last week's Sunday using JavaScript? I've searched through various sources with no luck. Hoping someone here can provide some guidance. ...

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

Link-defying button

I'm developing a website with a homepage that serves as an entry point to the rest of the site (it welcomes the user and allows them to click anywhere to access the main website). The following code accomplishes this: <template> <div onc ...

Adjust the array of column widths to align with the Bootstrap grid structure

Currently, I am in the process of transforming a system into a Bootstrap grid. However, I am facing a challenge on how to convert the existing widths, stored in an array in PHP, to the most suitable Bootstrap equivalent. Check out the phpfiddle demo The ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...

Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled. On the main ...

An effective method for utilizing a multiple choice input (presented as buttons) for entering data into a database using html, css, and js

I'm trying to figure out the coding process using buttons and input It's giving me a result, but only allows for a single choice Although I have limited experience with this, my goal is to create a multiple choice selection for days of the week ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

When using Material-UI's <Table/> component, an error is thrown stating that the element type is invalid

Struggling with material-ui Table is not familiar territory for me, especially since I have used it in numerous projects before. Currently, I am utilizing @material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33505c41567 ...

Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers: 'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}' I want to transform it into an array that looks like this: [ {marker: false, value: 'This is&ap ...

Accordion feature exclusively toggles the initial item

I am having an issue with the code in my index.php file. Only the first item in the accordion menu is showing up correctly. When I click on "Status" or "Repeated", I expect to see the sub-menu of the clicked item, but instead, I am getting the result from ...

Struggling to create a regular expression for a particular scenario

I'm dealing with nodes and currently faced with the task of applying a UNIX-like grep command to filter out specific content from an HTTP GET response. Below is the raw text received as the body variable: <?xml version="1.0" encoding="UTF-8" stand ...

Can a Vue app be created as a standalone application?

Can a Vue application be created without requiring Vue as a runtime dependency? For example, rather than having the browser load vue.js and the app like this <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src= ...

Troubleshooting: jQuery toggle() issue in Firefox 3.0.12

My jQuery code for toggling is working perfectly in IE6 but not in FF3. I'm wondering what could be causing this issue and if there is a workaround available. <button>Toggle Me</button> <p>Hi</p> <p>Learning jQuery&l ...

Implementing an event handler within a functional component using hooks in React

I'm currently exploring functional components and hooks. I have a component that retrieves an array of quotes from an API and is supposed to randomly select one to pass as a prop to a child component named "Quote". import React, {useState, useEffect} ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...