Implement a Sorted Index Finder - Implement a Sorted Index Finder

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

Could you assign the findIndex call to a variable, then reference the new variable?

1 Like

Thanks, I get it now. You mean I should save the result of findIndex() in a variable and use that instead of calling it twice. That definitely makes the code cleaner. I also see now that Math.ceil(num) isn’t needed, since the comparison should use num directly, I was actually trying to make the solution cleaner :sweat_smile: and it turned out as following:

const getIndexToIns = (arr, num) => {

  arr.sort((a, b) => a - b);

  let index = arr.findIndex((a) => a >= num);

  return index === -1 ? arr.length : index;

};

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.