Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 04, 2023 › #Array #HowTo

How to get the sum of an array in JavaScript using the reduce() method

In this article, you will learn how to use the reduce() method to get the sum of an array in JavaScript.

Here is an example :

<script>
 let myArray = [1, 2, 3, 4];
 let sum = myArray.reduce((x, y) => x + y);

 console.log(sum); // Output: 10
</script>

In the above example, we declare a new array called myArray and initialize it with four integers. Then, we use the reduce() method to iterate over each element in the array and add it to the sum variable.

The reduce() method takes a callback function. This function takes two arguments, x and y, which represent the previous and the current values in the array. In our case, we use an arrow function to add x and y together and return the result.

Finally, we print the value of the sum variable to the console and the output is 10.

How to get the sum of an array using the reduce() method. #

To get the sum of an array in JavaScript using the reduce() method, you can follow the following steps.

  1. Declare a variable to hold the array of values you want to sum.
  2. Use the reduce() method to iterate over each element in the array and add it to the sum variable.
  3. The reduce() method takes a callback function which has two parameters: the accumulator and the current value in the array.
  4. On each iteration, add the current value to the accumulator using the plus (+) operator.
  5. In the reduce() method, you can also specify an initial value for the accumulator. If you don't specify an initial value, it will use the first element in the array as the initial value.
  6. The sum variable will contain the total after the reduce() method finishes iterating over the array.
  7. Although reduce() can be a concise way to sum values in an array, be careful it can confuse you with its syntax.
save
listen
AI Answer
Write Your Answer
loading
back
View All