I think I came up with a similar solution to solution 2 on this challenge, but I do sort the array in mine.
I may have just gotten away with something I shouldn’t have while sorting though, since I did not use a compareFunction with sort…but it appears to still work fine.
function getIndexToIns(arr, num) {
let answer = 0;
let sortedArr = arr.sort();
console.log(sortedArr);
for (var i = 0; i < sortedArr.length; i++) {
if (sortedArr[i] < num) {
answer++;
}
}
return answer;
}
Can somebody clear up if this is a correct answer that could figure in the solutions or if I exploited something instead and why?
This line will not sort numbers. You can learn more about .sort here:
Other question, do you really need to sort numbers to decide the index of incoming number? If I take a queue ticket from the machine I don’t care the order of people in front of (and after) me, I only care how many them, right?
Yeah I already looked at the specifications of .sort, but the code worked nonetheless. Can you explain why?
It both passed the challenge without any errors, and also upon checking what “arr.sort();” returned on the console log, it returned the original array in the correct order as intended.
By default sort method thinks of items as strings, like so: ['414', '50', '9', '5', '12'] and 414 goes before 5, as it starts with 4, just like dad would go before e.