To the Min explainer


#1

The aim of this puzzle: Find the smallest number in the array using a loop and the smaller() function.

Walkthrough of the solution: To find the minimum of a list, you can compare the first 2 items and store smaller one as the current minimum. Then you compare that current minimum to the 3rd item, and store the smaller one. Then continue until you’ve compared each item to the current minimum. In the end, the minimum will be the smallest value from the array.

The smaller() function takes in 2 numbers and will output the smaller one. The minimum() function starts by creating a min variable that will store the current minimum, but it will start at 100 for now. The loop will go through each item in the array and hold it in a variable called num. What we need to do is compare the num to the min and store the smaller one as the new min.

Instead of min = num, we need to use min = smaller(min, num). You can also switch the order of the arguments.

Sample code solution:
(Tap below to reveal)

function smaller(a, b) {
  return a < b ? a : b;
}

function minimum(array) {
  let min = 100;
  for (let num of array) {
    min = smaller(min, num);
  }
  return min;
}
console.log(list);
console.log(minimum(list));

JavaScript Concepts: Binary Expression (<), Code Block (function), Conditionals (ternary statement), console.log(), Code Block (for loop)