Home >Web Front-end >JS Tutorial >How to Sort Arrays with Strings Containing Numbers in Natural Order?
Natural Array Element Sorting: Strings with Numbers
This article delves into the task of sorting arrays containing elements that combine strings and numbers in a natural order, where numerical sequences within the strings should be considered in the sorting process.
The Problem
Consider an array like this:
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
If we attempt to sort this array using a conventional sort function, we may end up with an incorrect order:
["IL0 Foo", "IL10 Baz", "IL3 Bob says hello", "PI0 Bar"]
The Solution: Natural Sorting
To achieve natural sorting, we can leverage the following JavaScript function:
function naturalCompare(a, b) { var ax = [], bx = []; a.replace(/(\d+)|(\D+)/g, function(_, , ) { ax.push([ || Infinity, || ""]) }); b.replace(/(\d+)|(\D+)/g, function(_, , ) { bx.push([ || Infinity, || ""]) }); while(ax.length && bx.length) { var an = ax.shift(); var bn = bx.shift(); var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]); if(nn) return nn; } return ax.length - bx.length; }
This function tokenizes the input strings into arrays of numerical and non-numerical values. It then compares the arrays lexicographically, taking into account the numerical values as integers and the non-numerical values as strings.
Example
Applying this function to the given array results in the desired natural sorting order:
test = [ "img12.png", "img10.png", "img2.png", "img1.png", "img101.png", "img101a.png", "abc10.jpg", "abc10", "abc2.jpg", "20.jpg", "20", "abc", "abc2", "" ]; test.sort(naturalCompare) document.write("<pre class="brush:php;toolbar:false">" + JSON.stringify(test,0,3));
This produces the following sorted array:
[ "", "abc", "abc2", "abc10", "abc10.jpg", "20", "20.jpg", "img1.png", "img2.png", "img10.png", "img12.png", "img101.png", "img101a.png" ]
The above is the detailed content of How to Sort Arrays with Strings Containing Numbers in Natural Order?. For more information, please follow other related articles on the PHP Chinese website!