0

I have following array:-

const a=["5.1.1","5.1.12","5.1.2"]

I want to sort the above to get the following:-

5.1.1,5.1.2,5.1.12

But if I call normal sort i get following.

 5.1.1,5.1.12,5.1.2

I tried implementing this using custom sort. Following is my code:-

let data = a.sort()
data.sort(function(x,y){
    const arrX = x.split(".")
    const arrY = y.split('.')
     if(parseInt(arrY[1]) >  parseInt(arrX[1])){
      return -1
    }
    if(parseInt(arrX[2]) > parseInt(arrY[2])){
      return 1
    }
})

return data

It works fine, but feels bit hacky. Does someone have a better solution for it?

Harkirat Saluja
  • 7,768
  • 5
  • 47
  • 73
  • Any solution will basically be the same, as `"12"` comes before `"2"`, and the only way is to split and convert to numbers – adeneo Nov 16 '16 at 12:50
  • 1
    basically you need for every part a check for the delta and if it is zero then proceed with the next part. if a value is different from zero, the return this value, or at the end zero. – Nina Scholz Nov 16 '16 at 12:59
  • 1
    thanks for helping out.. i was not able to put my query in words thats why could not find the already asked questions.. anyhow it helped and it works fine now @NinaScholz – Harkirat Saluja Nov 16 '16 at 15:48

0 Answers0