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

138
Visualizações
Really confused about sort in JS

today I was writing some code and I realized I cannot do x.push(5, 9).sort(); //wrong nor can I do x.sort(x.push(5, 9)); //wrong and had to do

x.push(5, 9);
x.sort();

I was wondering isn't there a way to make it one line?> also, what's the difference between the two lines below

x.sort((a, b) => a - b);
x.sort();
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

.push returns the new length of the array, not the mutated array. If you want to push and sort at the same time, consider creating a new array, then sorting that.

const sortedArr = [...arr, 5, 9].sort();
// or, .sort((a, b) => a - b)

.sort() without any arguments sorts each item in the array by comparing them lexiographically, as strings - resulting in unintuitive results like [1, 11, 2].

A custom callback allows you to customize the behavior - when an element of an array is compared against another, instead of using lexiographic comparison, the callback is invoked, and whether the return value is negative, positive, or 0 determines whether the two items get sorted before, after, or at the same (relative) position to the other. So, when sorting an array of numbers numerically, you always want to use something like (a, b) => a - b.

about 4 years ago · Juan Pablo Isaza Relatório

0

Another way to push and sort in one line is to use concat to create a new array which can be then be sorted:

const arr = [1, 6, 10]
const sortedArr = arr.concat([5, 9]).sort((a, b) => a - b)

console.log(sortedArr)

As @CertainPerformance has already noted, you must use a callback to correctly sort numeric values as string sorting of numbers produces incorrect results.

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