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

JavascriptObject Oriented ProgrammingProgramming

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

 Live Demo

<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

 

raja
Published on 27-May-2019 16:08:34
Advertisements