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

189
Vistas
JavaScript - Sort Array again using first column after order the second column with duplicates

I'm working to a script to reoder an array with javascript. When I've a duplicate value on the second column, I would like to order this duplicate value by index order and push it on new array.

The aim is to transform array like this :

myarr = [ 
    [5, 7]
    [2, 8]
    [3, 7]
    ];
    var valeurcroiss = myarr.sort(compareSecondColumn);
    var valeurdecroiss = valeurcroiss.reverse();
    valeurdecroiss.length = 3;
    
    function compareSecondColumn(a, b) {
         if (a[1] === b[1]) {
             return 0;
         }
         else {
             return (a[1] < b[1]) ? -1 : 1;
        }
    }

Result that I have:

[
0: (2) [5, 7]
1: (2) [3, 7]
2: (2) [2, 8]
];

Result I would like to have:

[
0: (2) [2, 8]
1: (2) [3, 7]
2: (2) [5, 7]
];

Thank you for your help

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

0

Replace this line

return (a[1] < b[1]) ? -1 : 1;

with:

return (a[1] < b[1]) ? 1 : -1;
about 4 years ago · Juan Pablo Isaza Denunciar

0

If there's a duplicate in the second column it'll already be arranged correctly if the first column is already arranged properly. So check for duplicates in index 0 and sort them out by index 1 and sort the rest by index 0.

const pairs = [[5, 7], [2, 8], [3, 7], [2, 6]];

let output = pairs.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);

console.log(output);

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