Implement a Sorted Index Finder - Implement a Sorted Index Finder

Tell us what’s happening:

Hello, I wanted to ask if this answer is correct or if there is something wrong with it.
It passes all tests, but I don’t know if maybe I’m hard coding something with the conditionals. Even though it makes sense, at least to me, to have them in those cases.

Your code so far

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);

  if (arr === []) {
    return 0;
  } else if (arr.findIndex(b => b > num) === -1) {
    return arr.length;
  } else {
  return arr.findIndex(b => b >= num);
  }
}

console.log(getIndexToIns([20, 3, 5], 19));

Your browser information:

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

Challenge Information:

Implement a Sorted Index Finder - Implement a Sorted Index Finder
https://www.freecodecamp.org/learn/javascript-v9/lab-sorted-index-finder/lab-sorted-index-finder[spoiler]This text will be blurred[/spoiler]

Summary

This text will be hidden

The correct way to check if an array is empty is if (arr.length === 0) {.
Your code works because if the arr is empty, it skips the first if statement check because the strict operator checks if they point to the same location. [] creates a new array in memory so arr will never be equal to [].
findIndex runs a check on an empty array, it will return -1.
Since -1 === -1 is true, then your code will return arr.length which is 0

1 Like

Try this instead:

  1. Sort the array
  2. Find the index where a number is greater than or equal to ‘num’,
  3. If no number(index) is bigger/equal (it returns -1), put it at the very end. Otherwise, return the index you found
1 Like

Oh, yeah. I forgot I am supposed to check for the length to see if the array is empty.

Besides that… What I understand is that the first conditional is not even necessary. It’s useless (besides being wrong and lucky to get the desired result), the tests pass without it.

So the rest of my code would be correct?

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);
  
  if (arr.findIndex(b => b >= num) === - 1) {
    return arr.length;
  } else {
    return arr.findIndex(b => b >= num);
  }
}

console.log(getIndexToIns([20, 3, 5], 19))

isn’t it a bit wasteful to do this twice?

1 Like

Yes, it is.

I suppose it should go into a variable?

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);

  const index = arr.findIndex(b => b >= num);

  if (index === - 1) {
    return arr.length;
  } else {
    return index;
  }

}

console.log(getIndexToIns([20, 3, 5], 19));