Finding the low high and range of an array of numbers

Hi Everyone!

I am trying to solve the following:

Using a loop, write a function getTheRange which finds the range (difference between high and low) of arr . The value returned should be an array with the low, high, and range.

I got some help on stackoverflow and the final answer ended up looking like this:

const getTheRange = (arr) => {
  let low = arr[0],
    high = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < low) {. //need need understanding from here down//
      low = arr[i];
    } else {
      high = arr[i];
    }
  }
  let range = high - low;
  return [low, high, range];
};

console.log(getTheRange([3, 2, 5, 4, 7, 9, 10])); // expect log [2, 10, 8]

Can someone plz just explain this? I don’t seem to understand how we set low and high = arr[0], then ask in the loop arr[i] < low ? and from there how does the code know this is the lowest value?

Sorry for question! Just really trying to understand the answer :smiley:

1 Like

First off, that code doesn’t work unless the highest value is in the final position of the array.

Second off, do you understand what arr[0] does? Do you understand what i represents in the for loop? Do you understand what arr[i] does?

@salomonj11
Please remove the dot (.) after the comment:
. //need need understanding…

So the code can run :smiley:

Explanation:

  • Have a reference value to compare with for low and high:
    let low = arr[0], high = arr[0]; // comma (,) was used to avoid using let again… DRY principle.

Note: it can be any index within the array… Aim is a reference to compare
Try: let low = arr[5], high = arr[5]; …in this case: low = 9, high = 9 in the console …then here let i = 0 is the first point not let i = 1

  • Loop through all numbers in the arr:
    since i = 0 - the initial value to compare, start with let i = 1
    as you go through, looping ask the questions:

is 2 (arr[1]) < 3
is 5 (arr[2]) < 3
is 4 (arr[3]) < 3
…
is 10 (arr[6]) < 3

If yes, it is the low, else it is the high.

I hope this helps.

1 Like

Just as an aside, I might suggest using Math.min/max (with spread).

I tried solving it that way but I did not know how to stop my range from repeating (due to the loop and question asking me to solve via loop)

const getTheRange = arr => {
  const newArray = []
  let range = 0

  const low = Math.min(...arr);
    newArray.push(low)

  const high = Math.max(...arr);
    newArray.push(high)

  for (let i = 0; i < arr.length; i++) {
     range = high-low;
     newArray.push(range)
   }

   return newArray;
}

You don’t need a loop.