-
Notifications
You must be signed in to change notification settings - Fork 3
/
44.1 reduce() in JS.html
44 lines (42 loc) · 1.44 KB
/
44.1 reduce() in JS.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head><title>Example of reduce() in JS</title>
</head>
<body>
<!--See previous code 44
-->
<script>
const arr=[5,4,2,8,7,6];
//find max inside arr
//without reduce() function
function MaxValue(arr){
let max=0;
for(var i=0;i<arr.length;i++){
if(arr[i]>max){ //if arr[i] i.e current element is greater then max then remove max's value with arr[i]
max=arr[i];
}
}
return max;
}
console.log(MaxValue(arr)) // o/p: 8
//with reduce() function(watch at 21:25)
const output=arr.reduce(function(max,currElement){
//we can use any name of accumulator and also for curr
if(currElement > max){ //i.e if current value is greate then max value/acc the max becomes currElement
max=currElement;
}
return max;
},0);
console.log(output); // o/p: 8
//find minimu value in an array using reduce
const arr2=[5,1,8,4,5,-6,0];
const minVal=arr2.reduce((min,currVal)=>{
if(currVal < min){
min=currVal;
}
return min;
},0)
console.log(minVal)
</script>
</body>
</html>