Reputation: 349
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?
Upvotes: 5
Views: 4403
Reputation: 598
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.
Upvotes: 8
Reputation: 252
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);
Upvotes: 2