nCardot
nCardot

Reputation: 6587

What's going on in this for loop?

This loop is from a solution for a freeCodeCamp challenge. I don't understand how it works -- what does decrementing i do? I'm totally clueless. Any help understanding would be greatly appreciated.

for (var i = arr[0]; i >= arr[1]; i--) {
  newArr.push(i);
}

Here's the full solution the for loop is from:

function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);

Upvotes: 2

Views: 59

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

I don't understand how it works -- what does decrementing i do ?

Here you're passing two values to your function as an array [1,5]

smallestCommons([1,5]);

Inside function smallestCommons first thing we are doing is sorting array in descending order

arr.sort(function(a, b) {
    return b - a;
});                       // arr = [5,1]

Now we are creating a newArray

let newArr = [];
  for (let i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
}
  • Here arr[0] = 5 and arr[1] = 1
  • So initial value of i is 5 and your condition is i >= arr[1]
  • We keep decreasing value of i untill it is less than arr[1] which is 1
  • So newArray will have value [5, 4, 3, 2, 1]

Upvotes: 3

Related Questions