Where do I Belong variable

Where do I Belong variable
0

#1

Tell us what’s happening:
I already solved this challange with this code but I don’t fully understad the way it works. In the first for loop where I rearrange the array “arr” I restart the variable “i” to -1, like this the code works, but my initial thougth was that I had to restart “i” to zero cuz i’m trying to make sure the programm checks always from arr[0]. If i=0 the programm leaves values in “arr” and never passes them to “mat”(a differente array).

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  let mat = [];
  let mini;
  let pos;

for (let i = 0;i<arr.length;i++) {
    mini = Math.min(...arr);
    if (arr[i] == mini){
    mat.push(arr[i]);
    arr.splice(i,1)
    i=-1;
    }
}

for (let j=0;j<=mat.length;j++){
  if ( mat === 0) {
    return 0;
  } else if (num <= mat[j] ) {
   return j;
 } 
}
return mat.length;
}
getIndexToIns([3,10,5], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/


#2

You need this because in the for loop it increments i. (i++)
So the next pass it is set to zero - the start of the array arr.