Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Calculating the index to insert into a sorted array

I want to insert new elements not at the end of the array, but directly into a suitable position. To do this, I use the .splice() method, in which I pass the callback function getSortPos()

acc.splice(getSortPos(acc, newAccount, compareAccounts), 0, newAccount)

This function takes an array, a new element and a compare function and calculates the appropriate position for inserting the new element

const getSortPos = (arr, el, cmpFn) => {
  let pos = 0;

  if (!arr?.length) {
    return pos;
  }

  while (cmpFn(arr[pos], el) < 0) {
    pos++;
  }

  return ++pos;
}

The solution seems to work at first glance but I think it has some flaws and does not look elegant.

I would be extremely grateful for any tips

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!