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

107
Vistas
Deterministic string compare in JS/TS?

I am looking for a deterministic way of sorting a list of strings.

Sorting a string of course often leads to the suggestion to use String.localeCompare. But the order must be deterministic, unrelated to the computer where it is running on.

The hardcore solution I came up with is hashing each string and compare these instead with a locale option en. Is there an easier solution?

The strings can be English, German, Chinese, Japanese, ...

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Oddly, what fits your requirements is...the default sort:

theStrings.sort();

That sorts according to the UTF-16 code units in the strings, which doesn't vary by computer/locale/whatever. It treats the strings as (effectively) a series of 16-bit numbers (Unicode code units, to be precise).

From the specification:

If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative Number if x < y, a positive Number if x > y, or a zero otherwise.

And the < and > operators are defined by the abstract IsLessThan operation in the specification, which compares by the code units in the string.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Two solutions:

  • use a specific locale, not the current one like localeCompare. JS supports this through the Intl.Collator:

    arr.sort(new Intl.Collator('en').compare)
    

    Choose whatever language you need.

  • use the standard lexicographic comparison that the builtin </> operators for strings supply:

    arr.sort((a, b) => +(a>b)||-(b>a))
    arr.sort()
    
about 4 years ago · Juan Pablo Isaza Denunciar
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