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

160
Vistas
How to sort strings in JavaScript by code point values?

I need to sort an array of strings, where elements are compared lexicographically as sequences of code point values, so that, for example, "Z" < "a" < "\udabc" < "�" < "💩".

  1. Is there a more efficient way of comparing strings, other than manually iterating over both of them and comparing the corresponding code points?
  2. What if it is guaranteed that the strings don't have any surrogate code points (but may have surrogate pairs, so "�" < "💩" should still hold)? Is there a more efficient procedure for this special case?

Note: there are many answers on StackOverflow explaining how to sort strings, but they either use the localeCompare order or the order defined by JavaScript comparison operators (which compare strings as sequences of UTF-16 code units). I am not interested in either of those.

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

0

How to sort strings in JavaScript by code point values?


It appears to be a surprisingly difficult problem. Here's a Proof Of Concept (POC) implementation:

'use strict';

function compareCodePoints(s1, s2) {
    const len = Math.min(s1.length, s2.length);
    let i = 0;
    for (const c1 of s1) {
        if (i >= len) {
            break;
        }
        const cp1 = s1.codePointAt(i);
        const cp2 = s2.codePointAt(i);
        const order = cp1 - cp2;
        if (order !== 0) {
            return order;
        }
        i++;
        if (cp1 > 0xFFFF) {
            i++;
        }
    }
    return s1.length - s2.length;
}

let s =[];
let s1 = "abc𞸁z";
let s2 = "abc𞸂z";

s = [s1, s2];
console.log(s);
s.sort(compareCodePoints);
console.log(s);

console.log()

s = [s2, s1];
console.log(s);
s.sort(compareCodePoints);
console.log(s);

console.log()

s1 = "a";
s2 = "";

console.log([s1, s2]);
console.log(compareCodePoints(s1, s2));
console.log([s2, s1]);
console.log(compareCodePoints(s2, s1));

$ node codepoint.poc.js
[ 'abc𞸁z', 'abc𞸂z' ]
[ 'abc𞸁z', 'abc𞸂z' ]

[ 'abc𞸂z', 'abc𞸁z' ]
[ 'abc𞸁z', 'abc𞸂z' ]

[ 'a', '' ]
1
[ '', 'a' ]
-1
$
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