skip to Main Content

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


  1. 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:

    let numbers = [12,23,34];
    
    function getSum(total, num) {
    return total + num;
    }
    
    console.log(numbers.reduce(getSum))
    

    Reduce will recursively call the function you have created. Num will represent an element of the array being passed in.

    Login or Signup to reply.
  2. 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.

    let numbers = [2, 4];
    const res = numbers.reduce((acc, cur) => acc + cur);
    console.log(res)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search