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\'
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'
. Tested in Chrome, Firefox, and IE11.
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. Docs link
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['1_Document', '11_Document', '2_Document'];
console.log(myArray.sort(collator.compare));