Min Max v2

Min Max v2

Given an array find which element is the biggest and which is the smallest

Example
let arr1 = [1,2,3,-4,100,34,-99] 100 Max -99 Min let arr2 = [75,23,6,-56,67,10]

let arr1 = [1,2,3,-4,100,34,-99]
function findMinandMax(arr) {

  let max = arr[0];
  let min = arr[0];

  arr.slice(1).forEach(x => {
    max = x > max ? x : max;
    min = x < min ? x :min;
  });
     return {min,max};
  
}
console.log(findMinandMax(arr1));  => 100 Max -99 Min

We create function called findMinandMax with parameter arr and local variable max = arr[0] and min=arr[0]

max= arr[0] and min=arr[0]

We loop the array given into the parameter arr with while loop with forEach arr.slice(1).forEach(x =>



Inside the for loop we check max = x > max ? x : max and min = x < min ? x : min

In the loop we use arr.slice(1) this means that we already checked the first number and delete it.

In the end we return {max,min}

comments powered by Disqus