The purpose
Sorts an array of strings (primarily filenames) in the same way Windows sorts filenames.
Background
Here are the results if we simply sort them as follows.
Code:
filenames.sort();
Input:
filenames = ["10","1","2","a","A","b","B","い","ア","あ"]
Output:
['1', '10', '2', 'A', 'B', 'a', 'b', 'あ', 'い', 'ア']
With this sort, sorting is performed based on the magnitude of the character codes.
Therefore, although you’d want numbers to be arranged as “1,” “2,” “10,” they are arranged as “1,” “10,” “2.”
Also, sorting for hiragana, katakana, and the alphabet returns results that differ from what one might intuitively expect.
Implementation
When using this implementation, files are sorted in the same way as Windows file names (I haven’t verified if they’re exactly the same, but I couldn’t find any differences, even with the ordering of kanji).
Code:
const collator = new Intl.Collator('ja-JP', { numeric: true, sensitivity: 'base' });
filenames.sort(collator.compare);
Input:
filenames = ["10","1","2","a","A","b","B","い","ア","あ"]
Output:
['1', '2', '10', 'A', 'a', 'B', 'b', 'あ', 'ア', 'い']
Numbers like “1,” “2,” and “10” are sorted in the order “1,” “10,” and “2,” which is the same as the desired order.
Additionally, hiragana, katakana, and the alphabet are sorted in a way that feels intuitive.
Change ‘ja-JP’ according to the character set of the string you’re using.
Actual implementation
It’s unlikely you’ll ever need to sort an array of just file names. Instead, you’ll almost always be sorting an array of file objects that contain file names.
To sort an array of objects that have a file name, you’d do the following (assuming files
is an array of objects, where each object has a name
property that stores the file name):
const collator = new Intl.Collator('ja-JP', { numeric: true, sensitivity: 'base' });
files.sort((a, b) => collator.compare(a.name, b.name));
comment