Computer >> Computer tutorials >  >> Programming >> Javascript

What is the use of Array.Reduce() method in JavaScript?


Array.Reduce()

The Array.Reduce() method executes the provided function(given by the user) to each element of the array, there by giving single output.In the given example, the provided function(function provided by user is addition) executes on each element of the array(1,2,3,4) there by returning a single output (10).

Example

<html>
<body>
<p>Sum of numbers in array: </p>
<script>
   const array = [1, 2, 3, 4];
   const sum = (firstValue, lastValue) => firstValue + lastValue;
   document.write(array.reduce(sum));
</script>
</body>
</html>

Output

Sum of numbers in array:10