JavaScript: Perform multiplication and addition on two arrays

I am looking for a way to multiply pairs of values in two arrays that have the same length, and then sum up the results based on their indexes.

As an example,

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];

The output would be 34 (4*2+3*3+4*3+5*1).

What is the most straightforward approach to achieve this?

Answer №1

let numbers1 = [2, 3, 4, 5];
let numbers2 = [4, 3, 3, 1];
console.log(numbers1.reduce(function(result, value, index){ return result + value * numbers2[index]}, 0));
34

This example demonstrates the use of a "functional" approach rather than an "imperative" one when calculating the dot product of two vectors. The functional approach, known for its brevity, is favored for simple function implementations like what the OP requested.

Answer №2

let total = 0;
for(let j=0; j< arrayOne.length; j++) {
    total += arrayOne[j]*arrayTwo[j];
}

Answer №3

let numbers1 = [1,2,3,4,5];
let numbers2 = [5,4,3,2,1];

numbers1.map(function(num, index){ //num represents numbers1[index]
 return numbers2[index] + num 
});

=>[6,6,6,6,6]

//To sum the elements of an array:

numbers1.reduce(function(num1, num2){
 return num1 + num2
});

=>15

To learn more about Array.map, click here. For information on Array.reduce, visit here

Answer №4

While there are probably more efficient solutions, I'll offer a recursive perspective for the sake of variety (it's particularly elegant in certain other programming languages). Please note that this function assumes both arrays are of equal length; you didn't specify what to do if they're not.

function calculateProductSum(arr1, arr2) {
    if(arr1.length)
        return arr1.pop() * arr2.pop() + calculateProductSum(arr1, arr2);

    return 0;
}

Edit:

katspaugh recommended swapping the order of returns for slightly improved efficiency (eliminates the need to check array length).

Answer №5

let nums1 = [2,3,4,5];
let nums2 = [4,3,3,1];


let total = 0;
for (let j=0; j < nums1.length; j++) {
  total += (nums1[j] * nums2[j]);
}

alert(total);

Give it a try here: http://jsfiddle.net/VQKPt/

Answer №6

let result = 0;
for(let j = 0; j < arr1.length; j++)
    result += arr1[j]*arr2[j];
console.log(result);

It's important to note that if arr2 is shorter than arr1, it will result in an error. However, since you mentioned they have equal lengths, I did not include a check for this scenario.

Answer №7

The most straightforward way to write this would have to be using a simple for loop:

var index, sum = 0;
for (index = 0; index < array1.length && index < array2.length; index++) {
    sum += array1[index] * array2[index];
}

Answer №8

function multiplyArrays (arrayOne, arrayTwo) {
    var newArray = (arrayOne,arrayTwo).map(x => x * x)
    return newArray
}

var firstArray = [3,6,9]
var secondArray = [3,6,9]
console.log(multiplyArrays(firstArray,secondArray))

Answer №9

Here is an example:

let total = 0;
for (let x=0, size = array1.length; x < size; x++) { // improved iteration
   total += array1[x] * array2[x];
}

Answer №10

This appears to be quite simple and easy for me

let sum = 0;
for (let index = 0; index < array1.length; index++){
    sum += array1[index] * array2[index];   
}

Answer №11

Here's a concise ES6 solution that utilizes the .reduce() function:

const calculateTotal = array1.reduce((total, value, index) => total + (value * array2[index]), 0)

Answer №12

Create functions that will perform the desired operations.

var sum      = function(a, b){ return a + b; };
var subtract = function(a, b){ return a - b; };
var multiply = function(a, b){ return a * b; };
var divide   = function(a, b){ return a / b; };

This allows for a clear and concise way to manipulate two arrays like so:

var array1 = [1,2,3];
var array2 = [2,4,8];

operateArrays(array1, array2, sum);      //[3, 6, 11]
operateArrays(array1, array2, subtract); //[-1, -2, -5]
operateArrays(array1, array2, multiply); //[2, 8, 24]
operateArrays(array1, array2, divide);   //[0.5, 0.5, 0.375]

This function is utilized here:

/**
* Divide each number of an array of numbers by another array of numbers
* @param  {Array}    arrayA  The array of numbers
* @param  {Array}    arrayB  The array of numbers
* @param  {Function} fn      Function that performs an operation
* @return {Array}            The resulting array
* @author Victor N. www.vitim.us
*/
function operateArrays(arrayA, arrayB, fn){
    if(arrayA.length!==arrayB.length) throw new Error("Cannot operate arrays of different lengths");
    return arrayB.map(function(b, i){
        return fn(arrayA[i], b);
    });
}

Answer №13

let numbers = [5,6,7,8];
let nums = [9,9,9,10];

You have the option to use:

let total = numbers.concat(nums).reduce((sum,num)=>sum+num);

or:

let total = numbers.map((n, i) => n + nums[i]).reduce((sum,num) => sum+num);

console.log(total);

Answer №14

Below are 3 different methods that achieve the same outcome. They are presented in order of increasing modern JavaScript syntax.

The initial method utilizes fundamental language features that have been in existence since the early days. This method is compatible with extremely old browsers like IE6.

The second method incorporates features from ECMASScript 5, which was introduced around 2009 and functions on IE9+.

The third method relies on ECMASScript 2015 arrow functions and is not supported on any version of IE, including IE 11 unless a build-step tool like Babel or Typescript is used for transpilation to ES5.

/**
 * Multiplies corresponding values of two arrays and then calculates the sum.
 * Compatible with all legacy browsers
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMAScript4(arr1, arr2) {
    var total = 0;
    for(var i = 0; i < arr1.length; i += 1) {
        total += arr1[i] * arr2[i];
    }
}

/**
 * Multiplies corresponding values of two arrays and then calculates the sum.
 * Compatible with all mainstream browsers except IE 8 and older.
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMAScript5(arr1, arr2) {
    // The map function creates a new array by multiplying values of arr1 and arr2
    // The reduce function sums up these products
    return arr1
        .map(function (value, index) { return value * arr2[index]; })
        .reduce(function (sum, current) { return sum + current; }, 0);
}

/**
 * Multiplies corresponding values of two arrays and then calculates the sum.
 * Compatible with all mainstream browsers except IE.
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMAScript2015(arr1, arr2) {
    // The map function creates a new array by multiplying values of arr1 and arr2
    // The reduce function sums up these products
    return arr1
        .map((v, i) => v * arr2[i])
        .reduce((sum, v) => sum + v, 0);
}



// Define your arrays
let arr1 = [2,3,4,5];
let arr2 = [4,3,3,1];

// Usage
let answer = sumOfProductsECMAScript4(arr1, arr2);
let answer2 = sumOfProductsECMAScript5(arr1, arr2);
let answer3 = sumOfProductsECMAScript2015(arr1, arr2);

Answer №15

When dealing with tasks similar to this, it is often recommended to leverage a library such as mathjs:

const array1 = [2, 3, 4, 5];
const array2 = [4, 3, 3, 1];
const results = math.dot(array1, array2);

Answer №16

Transform it using map and reduce functions

let numbers1 = [6,9,8,4];
let numbers2 = [5,6,7,8];

let finalResult = numbers1.map((value,index) => value * numbers2[index]).reduce((a, b) => a + b, 0)

console.log(finalResult)

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

Issue with Mongoose $in operator causing updates to only affect a single document

Having some issues with the "$in" operator in Mongoose. I have a User schema that includes an array of Card schema. The Card schema contains a 'score' field that I want to update based on a list of Card ids. Here's what I have attempted: Us ...

Just starting out with callback functions (using a callback as an argument)(Javascript)

Hello everyone, I'm a beginner here and I have a question about callback functions. Upon reading about them, I felt like I understood the concept. However, when I attempted to implement one in my code, things didn't go as planned. functio ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

How can we automatically insert non-set values as empty strings in MySQL using a for loop and query?

I am facing a challenge with inserting values from two arrays into a table with two columns. Each array can have anywhere from 1 to 5 set values. Currently, I have the following query provided to me in another SO question: INSERT INTO table_name (country ...

Using the video-js feature to play multiple videos simultaneously

Is it possible to play multiple videos using video-js functionality simultaneously? The answer is yes! Check out Fiddle 1 However, an issue arises when wrapping a trigger, such as a button, around the function that invokes playVideo(). This causes the v ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

Learn how to create a fading effect for an element when the mouse is inactive, and have it fade back in when the mouse is active again using J

There is a div with the ID "#top" that I want to have fade out after 3 seconds of mouse inactivity. Once the mouse is moved again, I would like it to fade back in. Any suggestions on how to achieve this effect? Appreciate your help! ...

What is the best way to generate a unique bootstrap card for every piece of submitted data?

I am trying to figure out how I can create a dynamic bootstrap card for each submitted data. When the form is submitted, a new card will be created and the data will be stored in that card. Each piece of data will be displayed in a column format similar to ...

Using jQuery to gradually diminish the text content within a text field

I am facing a challenge that has me scratching my head. Despite being well-versed in jQuery and JavaScript, I can't seem to figure this out. I've developed a basic plugin that clears a text input upon focus and displays the default value if no te ...

Changing the sliding underline effect in a jQuery navigation bar

Recently, I implemented a sliding underline element in my navigation bar. The idea is that when a link is hovered over, the underline smoothly transitions to that element. You can take a look at the codepen example here: https://codepen.io/lucasengnz/pen/e ...

The website appears to be loading in a unique way on mobile upon the second loading

While developing my personal website, I encountered a bug that occurs when accessing the site on my Android phone using Firefox or Chrome. The issue arises when the page initially loads correctly, but upon refreshing, the layout is displayed differently. ...

Remove an array object in React Redux

I recently started using Redux and I’ve encountered a major issue. Whenever I try to remove an object from an array, the map function stops working. Do you have any tips or suggestions? reducer.js: const initialState = { storeState: { name: ...

Building multidimensional arrays using the array module in Python

My goal is to generate a 2D array of integers by utilizing the array module. While I understand that it's straightforward to create a 2D array using lists, I am intrigued by the compact nature of the array module. from array import array a = array(&ap ...

struggling to send JSON data to PHP using AJAX

Here is the code snippet I am currently using. Javascript <script type="text/javascript"> var items = new Object(); items[0] = {'id':'0','value':'no','type':'img','filenam ...

It appears that the pixel sizes are different than what was originally designed

In my project, I have a header panel where the burger button is designed with a width of 32px and height of 24px. .header { display: flex; font-weight: bold; font-size: 50px; height: 100px; border: 1px solid black; position: relativ ...

Once the ajax request is finished, load only the <script> tags that have specific ids

I'm currently implementing infinite-scroll to dynamically load more content which includes <script> tags that need to be executed. To achieve this, I have created the following code as an ajax-callback: JS on load ajax callback: function a ...

Angular 5 in conjunction with Keycloak enabling access for non-authenticated users

I have a situation where I need to implement anonymous user access in my app, and for that purpose, I am incorporating the 'keycloak-angular' library along with Angular 5. The documentation instructs me to initialize the application as shown belo ...

Ways to sort choices in a dropdown box using data attributes?

I have a challenge where I need to filter the options in a select box with the id person based on data-attributes selected in another select box with the id invoice_project_id: Here is the HTML: <select id="invoice_project_id"> <option value=" ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...