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

109
Visualizações
keep indexes of original array of floats at sorting, and reverse sort to get back the original array afterwards js

I have this particular array of floats

segm3 = [0.0, 2.5, 3.62, 0.0, 2.5, 3.62, 0.0]

I desire to sort it while keeping the original indexes. This is my code:

var indices = Array.from(Array(segm3.length).keys())
.sort(function(a,b) { if (segm3[a] > segm3[b]) return 1;
 else if (segm3[a]<segm3[b]) return -1 ;else return 0;})

when I try to console.log the indexes I get this

[
  0, 3, 6, 1,
  4, 2, 5
]

It should be right, but after I sort segm3 how can I return back to form the original segm3 with the use of the indexes list ?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

To keep the original indexes you can use Array.prototype.map() and Array.prototype.sort():

Code:

const segm3 = [0.0, 2.5, 3.62, 0.0, 2.5, 3.62, 0.0]

const segm3SortedWithIndexes = segm3
  .map((f, i) => ({
    floatNumber: f,
    index: i, // <-- original index
  }))
  .sort((a, b) => a.floatNumber - b.floatNumber)
  
console.log('"segm3" with original index:', segm3SortedWithIndexes)

const result = segm3SortedWithIndexes.map(({ floatNumber: f }) => f)

console.log('"segm3" sorted:', result)

about 4 years ago · Juan Pablo Isaza Relatório

0

after segm3.sort(function(a,b) {return a-b})

just

let resultArr;
for(var i=0;i<indices.length;i++){
        resultArr[indices[i]]=segm3[i]
    }

It was simple as that but my mind was melt

about 4 years ago · Juan Pablo Isaza Relatório

0

Having got the indices sorted according to the values in segm3, if you then sort segm3 you can then restore the original ordering of segm3 by using the indices array to extract the values from the sorted segm3 array:

const segm3 = [0.0, 2.5, 3.62, 0.0, 2.5, 3.62, 0.0]
console.log(JSON.stringify(segm3))

let indices = Array.from(Array(segm3.length).keys())
  .sort((a,b) => segm3[a] - segm3[b])

console.log(JSON.stringify(indices))

segm3.sort((a,b) => a - b);
console.log(JSON.stringify(segm3))

let origsegm3 = indices.map(i => segm3[i])
console.log(JSON.stringify(origsegm3))

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