How to Sort an Array of Filenames Containing Strings with Numbers?

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

Related Questions

⦿Is SonarQube Compatible with Java 9?

Explore whether SonarQube supports Java 9 including details on compatibility configurations and common issues to watch out for.

⦿Understanding the Purpose of Annotation#annotationType() in Java

Learn how AnnotationannotationType in Java works its purpose benefits and common use cases.

⦿How to Properly Handle Exceptions in Java Streams Without Losing Value?

Learn how to effectively catch exceptions in Java streams ensuring you retain the correct values during error handling.

⦿Understanding Why Java 8 Stream `distinct()` Might Not Be Working

Explore common issues with Java 8 Stream distinct and learn how to effectively use it in your applications.

⦿What Percentage of Android Phones Utilize Little-Endian Architecture?

Explore the percentage of Android phones operating on littleendian architecture and its implications on software development.

⦿Should the Keystore Password and PKCS12 Certificate Password Be the Same?

Explore whether the keystore password should match the PKCS12 certificate password and learn best practices for password management in Java security.

⦿How to Resolve a Dozer Mapping Exception in Spring Boot DevTools?

Learn how to fix Dozer mapping exceptions related to Spring Boot DevTools with expert tips and code examples.

⦿Is the Java Calendar WEEK_OF_YEAR Field ISO-8601 Compliant?

Explore the compliance of Java Calendars WEEKOFYEAR with ISO8601 standards. Get detailed insights solutions and common mistakes.

⦿How to Resolve 'LayoutResultCallback is Not Public' Error When Generating PDFs

Learn how to fix the LayoutResultCallback is not public in LayoutResultCallback cannot be accessed from outside package error during PDF generation.

⦿Understanding the Order of Stream Operations on List Elements in Java

Discover the sequence of stream operations applied to list elements in Java including filtering mapping and reducing operations.

© Copyright 2025 - CodingTechRoom.com