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?
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?
Share Improve this question edited Jun 30, 2021 at 13:55 D M 7,1974 gold badges18 silver badges37 bronze badges asked Jun 30, 2021 at 13:53 nsog8sm43xnsog8sm43x 3495 silver badges17 bronze badges 6- Please post your algorithm, with your explanation to it and what exactly failed, so we can help you resolve it together – GalAbra Commented Jun 30, 2021 at 13:54
- Please edit your question to show what research you've done and any attempts you've made to solve the problem yourself – DecPK Commented Jun 30, 2021 at 13:54
- Both arrays are expected to be of the same length? – Snirka Commented Jun 30, 2021 at 14:00
- @Snirka yes, both have the same length – nsog8sm43x Commented Jun 30, 2021 at 14:02
- @nsog8sm43x see if the answer below satisfy you – Snirka Commented Jun 30, 2021 at 14:04
2 Answers
Reset to default 8You 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.
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);