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

110
Vistas
Array.sort method not working when sorting by property

I have a basic array, that I'm trying to sort by the source property:

const arr = [
    { source: '64', target: '63' },
    { source: '61', target: '64' },
    { source: '114', target: '63' },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

But this leaves the array untouched. What am I doing wrong here?

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

0

I think you are over complicating it.

arr.sort((a,b) => a.source - b.source);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Convert your strings in the array to numbers.

const arr = [
    { source: 64, target: 63 },
    { source: 61, target: 64 },
    { source: 114, target: 63 },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to convert strings to integers, before making comparisons, otherwise non-empty string will coerce to true and you are basically doing true > true inside your sort resolver.

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