I want to use an array as the argument of a function to do some calculation with them, but I don’t know how to make the elements of the array variables that the function can use. i am working on java.script .
I am starting programming so I try to make it as simple as possible with the basic concepts that I have
let numbers=[m1,m2]
function sum( numbers){
let result = m1+m2
return (result);
}
console.log(numbers[2,4].reduce(sum))
2
Answers
Here is the syntax for reduce: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Here is an example of how you can use reduce to sum the elements of a javascript array:
Reduce will recursively call the function you have created. Num will represent an element of the array being passed in.
No need to use a function for that,
reduce()
is enough for your needs.acc
is the accumulator, it will store the total value of your sum in each iteration.cur
is the current value, in this case on the first iteration your current value will be 2 and the next one will be 4.