Home > Software engineering >  keep indexes of original array of floats at sorting, and reverse sort to get back the original array
keep indexes of original array of floats at sorting, and reverse sort to get back the original array

Time:06-01

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 ?

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

  • Related