Where do I belong - How can this solution be right?

Tell us what’s happening:
Somehow this solution got passsed even though I yet do not understand how it can work when num = 0.

  **Your code so far**

function getIndexToIns(arr, num) {
let ind = 0;
let arrSorted = arr.sort();
num = Math.floor(num);
for (let i =0; i < arrSorted.length; i++) {
  if (arrSorted[i] < num)
  ind++
}
return ind
}

console.log(getIndexToIns([40, 60], 50));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0

Challenge: Where do I Belong

Link to the challenge:

Well, it certainly does:

console.log(getIndexToIns([1, 2], 0));
// 0
console.log(getIndexToIns([-1, 1], 0));
// 1
console.log(getIndexToIns([-2, -1], 0));
// 2

Perhaps if you put some logs in there it will help you understand:

function getIndexToIns(arr, num) {
  let ind = 0;
  let arrSorted = arr.sort();
  num = Math.floor(num);
  for (let i = 0; i < arrSorted.length; i++) {
    console.log('for loop, i =', i, '   comparing', num, 'to', arrSorted[i])
    if (arrSorted[i] < num) {
      ind++
      console.log('incrementing to', ind)
    }
  }
  return ind
}

Since you have a working solution, I surrounded it with [spoiler][/spoiler] tags.

Thank you! I’ll take that into account for future posts.

1 Like

Cool. Were you able to understand the how the function works?

1 Like

Yes I did, but the reasoning does not come naturally for me when num = 0 so I will have to go back an redo this exercise to see if there is any other way of coming up with the solution. Thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.