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
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
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))