Tell us what’s happening:
For some reason arr.sort() isnt sorting [5, 3, 20, 3] properly, it returns [20, 5, 3, 3] instead of [3, 3, 5, 20]. For all other arrays it works but not this one, any help is appreciated.
Your code so far
function getIndexToIns(arr, num) {
arr.sort();
console.log(arr)
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) {
return arr.indexOf(arr[i])
}
}
return arr.length;
}
console.log(getIndexToIns([5, 3, 20, 3], 5));
Your browser information:
User Agent is: Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Where do I Belong
MDN describes what is happening here. By default, .sort sorts your array alphabetically.
The discussion on MDN should help.
Side note - after you get the version with .sort working, I’d try to come up with a solution that doesn’t use .sort. That .sort changes the array, and it changes the array outside of your function. That’s usually considered “rude” behavior for a function to change data outside of its scope unless its explicitly supposed to.