Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  53] [ 3]  / answers: 1 / hits: 171646  / 14 Years ago, mon, may 10, 2010, 12:00:00

I'm looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.


E.g.,


'123asd'
'19asd'
'12345asd'
'asd123'
'asd12'

turns into


'19asd'
'123asd'
'12345asd'
'asd12'
'asd123'

This is going to be used in combination with the solution to another question I've asked here.


The sorting function in itself works, what I need is a function that can say that that '19asd' is smaller than '123asd'.


I'm writing this in JavaScript.


I'm looking for a function for natural sorting.


More From » sorting

 Answers
200

This is now possible in modern browsers using localeCompare. By passing the numeric: true option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'. It was tested in Chrome, Firefox, and Internet Explorer 11.


Here's an example. It returns 1, meaning 10 goes after 2:


'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})

For performance when sorting large numbers of strings, the article says:



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.





var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['1_Document', '11_Document', '2_Document'];
console.log(myArray.sort(collator.compare));




[#96829] Thursday, May 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taliac

Total Points: 84
Total Questions: 114
Total Answers: 114

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
taliac questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
Mon, Jan 13, 20, 00:00, 4 Years ago
;