Things I want to do
This sorts an array of strings (mainly filenames) in the same way as Windows sorts filenames.
background
Let’s look at the results when we simply sort as follows.
code:
filenames.sort();input:
filenames = ["10","1","2","a","A","b","B","い","ア","あ"]Result:
['1', '10', '2', 'A', 'B', 'a', 'b', 'あ', 'い', 'ア']This sorting method sorts characters by their character encoding (higher or lower).
Therefore, the numbers should be arranged as ‘1’, ‘2’, ’10’, but they appear as ‘1’, ’10’, ‘2’.
Furthermore, sorting results for hiragana, katakana, and the alphabet can differ from what you might expect.
implementation
The following implementation allows you to sort files in a similar way to Windows filenames (I haven’t verified if they are exactly the same, but I couldn’t find any differences, including the arrangement of kanji characters).
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","い","ア","あ"]Result:
['1', '2', '10', 'A', 'a', 'B', 'b', 'あ', 'ア', 'い']The numbers will be arranged in the same order as you would want them to be in the sequence ‘1’, ‘2’, ’10’, so they will be in the sequence ‘1’, ’10’, ‘2’.
Furthermore, hiragana, katakana, and the alphabet are sorted in a way that closely resembles intuition.
Please change ja-JP depending on the character set of the string you are using.
Actual implementation
In practice, you rarely sort an array of filenames; you almost always sort the file objects that contain the filenames.
To sort an array of objects that contain filenames, you would do the following: (files is an array of objects that have name, which stores the filenames.)
const collator = new Intl.Collator('ja-JP', { numeric: true, sensitivity: 'base' });
files.sort((a, b) => collator.compare(a.name, b.name));

コメント