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

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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