Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda