How to multiply elements of an array by elements from another array with the same index?
Asked Answered
J

2

5

I am trying to write an JS algorithm in which I have two arrays.

The value of the first one will have different numerical values. The second array will be constant, say for example [5, 3, 6, 8].

Now I would like to multiply the values from the first array, by the corresponding index value from the second array, so having for example such a first array: [3, 7, 2, 5] it would look like this: 5*3, 3*7, 6*2, 8*5.

From the result I would like to create a new array, which in this case is [15, 21, 12, 40].

How can I achieve this result?

Jaggy answered 30/6, 2021 at 13:53 Comment(6)
Please post your algorithm, with your explanation to it and what exactly failed, so we can help you resolve it togetherAccessory
Please edit your question to show what research you've done and any attempts you've made to solve the problem yourselfBlooper
Both arrays are expected to be of the same length?Genagenappe
@Genagenappe yes, both have the same lengthJaggy
@Jaggy see if the answer below satisfy youGenagenappe
@Genagenappe yes, I am very satisfied with this solution :) thank you very much !Jaggy
G
8

You can use map() and use the optional parameter index which is the index of the current element being processed in the array:

const arr1 = [3, 4, 5, 6];
const arr2 = [7, 8, 9, 10];

const mulArrays = (arr1, arr2) => {
    return arr1.map((e, index) => e * arr2[index]);
}

console.log(mulArrays(arr1, arr2));

This is assuming both arrays are of the same length.

Genagenappe answered 30/6, 2021 at 14:2 Comment(0)
D
2

You can simply use for loop -

var arr1 = [5, 3, 6, 8];
var arr2 = [3, 7, 2, 5];
var finalArr = [];
for (var i = 0; i < arr1.length; i++) {
    finalArr[i] = arr1[i] * arr2[i];
}
console.log(finalArr);
Dogear answered 30/6, 2021 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.