Question
How can I sort an array of filenames that include both strings and numbers?
const filenames = ['file10.txt', 'file1.txt', 'file2.txt', 'file20.txt'];
const sortedFilenames = filenames.sort((a, b) => {
const numA = parseInt(a.match(/\d+/g) || 0);
const numB = parseInt(b.match(/\d+/g) || 0);
return numA - numB;
});
Answer
Sorting an array of filenames that contain both strings and numbers can be tricky due to the mixed data types. Here, I'll explain a method to achieve a numerical sort that maintains logical order, rather than simple lexicographic order.
const filenames = ['file10.txt', 'file1.txt', 'file2.txt', 'file20.txt'];
const sortedFilenames = filenames.sort((a, b) => {
const numA = parseInt(a.match(/\d+/g) || 0);
const numB = parseInt(b.match(/\d+/g) || 0);
return numA - numB;
});
console.log(sortedFilenames); // Output: ['file1.txt', 'file2.txt', 'file10.txt', 'file20.txt']
Causes
- Lexicographic sorting treats numbers as strings, leading to incorrect order (e.g., 'file2' comes after 'file10').
- Without proper extraction of numeric values, sorting will not yield desired results.
Solutions
- Use a custom sort function that extracts numbers from the filenames, comparing those values numerically.
- Leverage regular expressions to find numbers in the filenames.
Common Mistakes
Mistake: Not using a custom sort function and relying on default array sort, which leads to incorrect ordering.
Solution: Implement a custom sort function that extracts and compares numeric parts of the filenames.
Mistake: Ignoring the presence of non-numeric characters and sorting as full strings.
Solution: Use regex to isolate numeric values before sorting.
Helpers
- sort array filenames
- sorting strings with numbers
- JavaScript array sort
- custom sorting function
- programming tips