Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




reduce() - FUNCTION


reduce() Function is used to reduce the elements of the array to a singe value(Say by adding all the values) starting from left to right.


Let us say we have the below array with four elements.


var x = [5, 8, 2, 9]
JavaScript reduce()-Function


And want to add all the numbers 5+8+2+9 = 24.


And reduce() function helps us achieve the above.


Let us see in the below example.


Example :



<html>
<body>  
<script>

	function myFunction(tot, num){
		return tot+num
	}
	
	var x = [5, 8, 2, 9]
	var y = x.reduce(myFunction)
	
    document.write(y)
	    
</script>      
</body>
</html>


Output :



  24

So, in the above code we have array that has 4 numbers.


var x = [5, 8, 2, 9]
JavaScript reduce()-Function


And we have declared a function named myFunction() that adds all the values of the array and returns thet result.


function myFunction(tot, num){
	return tot+num
}

There are two arguments, tot and num. You can consider tot keeps track of the total and num value of the current element.


Next, when the reduce() Function is called.


var y = x.reduceRight(myFunction)

It executes 4 times (i.e. Length of array times) and calls myFunction() starting from the left most element i.e. 5, adding all the elements returning the final result as 24.