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

154
Visualizações
What is the purpose of subtracting from Math.random?

I'm going through javascript.info and doing the practice tasks for Array Methods. This one is "Shuffle an array" and the instructions are:

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array.

I couldn't figure it out so I looked it up but now im struggling to understand it. What does the ".5 -" do in the line .5 - Math.random?

let arr = [1, 2, 3];

function shuffle(array) {
    return arr.sort((a, b) => .5 - Math.random())
}
console.log(shuffle(arr))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The .sort callback will iterate over the elements of the array and sort them depending on the value returned by the callback. If a negative number is returned, a will be sorted before b - if a positive number is returned, b will be sorted before a.

Math.random() returns a number between 0 and 1. If it's subtracted from 0.5, you get a random number between -0.5 and +0.5. So doing

(a, b) => .5 - Math.random()

is a way to get the callback to return a positive number 50% of the time and a negative number 50% of the time, and will randomly shuffle the array to a certain extent.

That said, "sorting" in this manner will produce biased results. Use a better algorithm.

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