Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
This program will teach us how to find the maximum value in a given array.
1. First Approach using for loop.
var arr = [111,113,14,12,15,0,1];
let max = arr[0];
for(let val of arr){
if(val>max){
max = val;
}
}
console.log('Maximum value',max)
Output: 113
2. The second approach uses the sort method.
var arr = [111,113,14,12,15,0,1];
let newarr = [...new Set(arr)];
newarr = newarr.sort(function(a,b){ return a-b; }).reverse();
console.log('Maximum value is',newarr[0]);
Output: 113
3. The third approach uses the Math. max().
var arr = [111,113,14,12,15,0,1];
let newarr = [...new Set(arr)];
console.log('Maximum value is',Math.max(...newarr));
Output: 113