0

I have an array that looks like the following:

[
{"version": "1.1"},
{"version": "1.2"},
{"version": "1.11"}.
{"version": "test1.3"},
{"version": "1.12"},
{"version": "1.4"}

]

I would like to order the objects in the following way.

1.1
test1.3
1.4
1.11
1.12

I'm not sure how I can sort the objects in my array to look like the above. I could iterate through with a loop and convert all the strings to numbers and then order by number? However some of the version have words in them such as "test1.3", so I'm not sure how that would work.

How can I sort my array in this example?

benjaminadon
  • 143
  • 3
  • 13
  • 1
    Why isn't the order `[ '1.1', '1.11', '1.12', 'test1.3', '1.4' ]`? At least that way the numbers are ascending. – Gershom Maes Jul 11 '19 at 21:38
  • May because they are version numbers and not decimal numbers, so 0.3 is not the same as for 0.30 – Santi Jul 11 '19 at 21:41
  • 1
    Have a look at [natural sort](https://stackoverflow.com/questions/15478954/sort-array-elements-string-with-numbers-natural-sort) for inspiration. You just have to ignore the text parts. – Bergi Jul 11 '19 at 21:41
  • how 1.1, test1.3, 1.4, 1.11, 1.12 are sorted? – Sima Amini Jul 11 '19 at 22:06
  • So if you use the compare function from the answer marked as duplicate you would call the following (versions is your array): versions.sort((a, b) => naturalCompare(a.version.replace(/\D/g, ''), b.version.replace(/\D/g, ''))) – Daniel W. Jul 11 '19 at 22:07

0 Answers0