Where do I Belong failing last tests

Tell us what’s happening:
I cannot get the getIndexToIns([], 1) should return 0 . test to pass.
I have an if statement that evaluates if the length of the array is less than 1 and if so set index to 0 but it does not seem to be working.

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
 var sort = arr.sort(function(a, b){return a-b});
 var index;
var last = sort.length;
 for (var i = 0; i < sort.length; i++) {
      if (sort.length < 1) {
        index = 0;
      }
    else  {
         if (sort[last -1] < num) {
          index = last;
         }
          
          }
 while (sort[i] >= num) {
 index = sort.indexOf(sort[i]);
  }
    }
    //console.log(sort);
    return index;
 }
    
    
    
 

getIndexToIns([], 1);

Your browser information:

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

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

If the array is empty, the body of the for loop will never execute.

 for (var i = 0; i < sort.length; i++) {

This initializes i to 0. Then it checks the length of sort.length. If i is not less than sort.length, then it does not continue.

1 Like
  // Find my place in this sorted array.
 var sort = arr.sort(function(a, b){return a-b});
 var index;
var last = sort.length;
if (sort.length < 1) {
        index = 0;
      }
 for (var i = 0; i < sort.length; i++) {
      
  if (sort[last -1] < num) {
      index = last;
 }
          
          
 while (sort[i] >= num) {
 index = sort.indexOf(sort[i]);
  }
    }
    //console.log(sort);
    return index;
 }
    
    
    
 

getIndexToIns([], 1);

Thank you. I moved that if statement out of the for loop and it passed.

Congratulations. Happy coding!

Thanks will do. Im sure my code looks abysmal to experienced coders but hey I am learning.

a7e1a5c9-c048-4006-bcaf-4537a5008f88

one quick question if I would have made it for (var i = 0; i <= sort.length; i++) {

would it have computed?

You would have ended up with an index out of bounds error because the last iteration of the loop would be trying to access sort[sort.length], which doesn’t exist because indexing starts at zero.

What you could do though, is just initialize index to 0 before the loop.

Thank you. It is always the simple answers that get you. I was thinking too much about it to think of that apparently.

It’s a common trap we all fall into, trying to be extra clever.

1 Like