Home > Article > Web Front-end > How to Sort an Array of Strings Containing Numbers in Natural Order?
Natural Sorting of Array Elements (String with Numbers)
Sorting an array of strings containing numbers in a "natural" order poses a challenge. The default sorting algorithm treats each character individually, resulting in an unnatural order.
Proposed Solution: NaturalCompare Function
To overcome this issue, a JavaScript function called naturalCompare can be utilized. This function follows a specific algorithm to compare strings, considering both numeric and alphanumeric portions separately.
Implementation of naturalCompare
The function parses each string into an array of alternating numeric and non-numeric segments. This allows it to compare the numeric segments as integers and the non-numeric segments lexicographically. The function returns a value indicating whether the first string is less than (-1), equal to (0), or greater than (1) the second string.
Sorting Using naturalCompare
To sort an array using natural order, apply the naturalCompare function to the sort method. This ensures that the strings are compared using natural sort criteria.
Example Usage
Here's an example of using the naturalCompare function to sort an array of strings containing numbers:
// Input array const array = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]; // Sort using naturalCompare array.sort(naturalCompare); // Output array console.log(array); // ["IL0 Foo", "IL3 Bob says hello", "IL10 Baz", "PI0 Bar"]
Additional Notes
The above is the detailed content of How to Sort an Array of Strings Containing Numbers in Natural Order?. For more information, please follow other related articles on the PHP Chinese website!