1

I'm trying to sort this array.

array = new Array();
array[0] = "Population23"
array[1] = "Population3"

So i used the sort function like this array.sort() And it gives me :

array[0] = "Population23"
array[1] = "Population3"

Instead of :

array[0] = "Population3"
array[1] = "Population23"

Why ? And how can i fix this to give me the "Instead of" result ?

Zahreddine Laidi
  • 560
  • 1
  • 7
  • 20
  • Which type of sort do you need? sort goes alphabetically, so it makes sense what it gives in output – axel Nov 29 '19 at 09:54
  • What are you basing your expected result on? The length of the string? – StudioTime Nov 29 '19 at 09:54
  • Nice find, @Nina! – T.J. Crowder Nov 29 '19 at 09:55
  • No, just the Population3 is less than Population23, because of the 3 and 23. So how can i change this ? – Zahreddine Laidi Nov 29 '19 at 09:56
  • 2
    The default sort is *lexicographic*: it compares the strings character by character, (more accurately: code unit by code unit) and stops when it finds a difference. Since `"2"` is less than `"3"`, it stops when it reaches that point of the strings, saying that `"Population23"` is less than `"Population3"` (because in string terms, it is). If you want to compare them lexicographically except for the numbers at the end, you'll have to write a custom comparison function. – T.J. Crowder Nov 29 '19 at 09:57
  • When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. `const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'}); const array = ['Population23', 'Population3']; console.log(array.sort(collator.compare));` by passing `numerice:true` option it browsers recognize numbers and you can do case-sensivity:'base' for it aswell – Muhammad Ali Nov 29 '19 at 10:00
  • refer to link https://stackoverflow.com/questions/29180284/can-javascript-sort-strings-containing-numbers – Mohit Kumar Bordia Nov 29 '19 at 10:01

0 Answers0