Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement