Tell us what’s happening:
I completed the Sorted Index Finder lab and my solution passes the tests, but I want to know whether there is a cleaner or more idiomatic approach that still follows the lab requirement to use both sort() and findIndex()
My question is:
Is there a better way to write this logic?
Is using Math.ceil(num) actually correct here, or unnecessary?
Can this be simplified without calling findIndex() twice?
Your code so far
const getIndexToIns = (arr, num) => {
arr.sort((a, b) => a - b);
let index;
if (arr.findIndex((a) => a >= Math.ceil(num)) === -1) {
index = arr.length;
} else {
index = arr.findIndex((a) => a >= Math.ceil(num));
}
return index;
};
console.log(getIndexToIns([1, 2, 3, 4], 1.5));
console.log(getIndexToIns([40, 60], 50));
console.log(getIndexToIns([10, 20, 30, 40, 50], 30));
console.log(getIndexToIns([3, 10, 5], 11));
console.log(getIndexToIns([], 5));
My question is:
Is there a better way to write this logic?
Is using Math.ceil(num) actually correct here, or unnecessary?
Can this be simplified without calling findIndex() twice?
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36
Challenge Information:
Implement a Sorted Index Finder - Implement a Sorted Index Finder