OneBite.Dev - Coding blog in a bite size

find the minimum and maximum element in an array in Javascript

Code snippet on how to find the minimum and maximum element in an array in Javascript

  // Define the array variable
  const array = [2, 3, 5, -1, 7, 10];
 
  // Initialize the variable to store minimum and maximum
  let min = array[0];
  let max = array[0];
  
  // Loop through the array 
  // and update min and max depending on the value
  for (let i = 1; i < array.length; i++) {
    if (array[i] < min) {
      min = array[i];
    } else {
      max = array[i];
    }
  }
  
  // Print results
  console.log("Minimum element is", min);
  console.log("Maximum element is", max);

This code will find the minimum and maximum elements of an array. First, the array variable is defined with the values that we want to work with. Then, we assign two variables, min and max, to the same value as the first element of the array.

The next step is to loop through the array, starting at the second element. For each element, we check if current element’s value is less than the minimum variable. If it is, we update the minimum variable with the element’s value. If it isn’t less than the minimum variable, then it must be greater than the maximum variable, so we update the maximum variable.

Finally, we print the results of our minimum and maximum variables.

javascript