Search code examples
javascriptnumbers

Finding lowest and highest number number value in an Array


I am struggling to workout how this code is working, how is the maxNum part working? maxNum[0] < numbers[i] how is it grabbing the last number from the array?

function sortThem(numbers) {

  let minNum = numbers[0]
  let maxNum = numbers[0]

  for (let i = 0; i < numbers.length; i++) {
    if (minNum > numbers[i]) {
      minNum = numbers[i]
    } else if (maxNum < numbers[i]) {
      maxNum = numbers[i]
    }
  }

  console.log(maxNum)

  const minMax = [minNum, maxNum]
  return minMax

}

const results = sortThem([2, 9, 10, 17, 45])

console.log(results)


Solution

  • Both start at 2 in this example

    let minNum = numbers[0]//equals first element in the numbers array and thats 2 in this example
    let maxNum = numbers[0]// equals 2 as well
    

    Then you start to iterate thru the numbers array

    Lets cover how you get your lowest number first:

    if(minNum > numbers[i]){
    
    1st loop
    minNum = 2 not greater than 2, nothing happens
    2nd loop 
    minNum = 2 not greater than 9, nothing happens
    3rd loop
    minNum = 2 not greater than 10, nothing happens
    4th loop
    minNum = 2 not greater than 17, nothing happens
    last loop
    minNum = 2 not greater than 45, nothing happens
    

    minNum = never changes during the entire iteration becuz no number lesser than 2 was found so it keeps the initial value

    Now for the maxNum:

     } else if (maxNum < numbers[i]){
    
    1st loop
    maxNum= 2, numbers[i]=2, numbers[i] not greater than maxNum, nothing happens
    2nd loop 
    maxNum= 2, numbers[i]=9, numbers[i] is greater than maxNum, maxNum=9 now
    3rd loop
    maxNum= 9, numbers[i]=10, numbers[i] is greater than maxNum, maxNum=10 now
    4th loop
    maxNum= 10, numbers[i]=17, numbers[i] is greater than maxNum, maxNum=17 now
    last loop
    maxNum= 17, numbers[i]=45, numbers[i] is greater than maxNum, maxNum=45 now
    

    maxNum will overwrite itself as long as you can find a number that's higher than the value previously stored. Hopefully that explains what you don't understand