My solution was:
Spoiler Alert!
function getIndexToIns(arr, num) {
function sorter(a, b) {
return a-b;
}
function comparator(i) {
return i >= num;
}
let sortedArr = arr.sort(sorter);
let seekedIndex = sortedArr.findIndex(comparator);
return (seekedIndex == -1 && arr.length == 0) ? 0
: (seekedIndex == -1 && arr.length > 0) ? arr.length
: seekedIndex;
}
After passing all the tests I’ve checked solutions proposed here to see how far I was from most elegant one.
My code was similar to the intermediate solution with findIndex method (yay!), but it can handle properly as well the case with getIndexToIns([40, 60, 4, 120], 50), on the contrary to the proposed solution.
Not sure why this code:
Intermediate Solution
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr.sort((curr, next) => curr > next)
.findIndex((currNum)=> num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
getIndexToIns([40, 60, 4, 120], 50);
returns 1 though.
Any ideas?