Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!