Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda