Natural Sorting of Array Elements with String and Numeric Components
In some cases, we encounter arrays containing elements that follow a particular format, such as strings with embedded numbers. Sorting such arrays in a logical order, known as "natural sorting," presents a challenge.
Challenge
Consider an array like:
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
To achieve the desired sorting:
["IL0 Foo", "IL3 Bob says hello", "IL10 Baz", "PI0 Bar"]
Solution
Natural sorting requires a comparison function that considers both the numeric and textual components within each element. Here's a JavaScript implementation:
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; }
Explanation
Example
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)
The sorted array would be:
["", "20", "20.jpg", "abc", "abc2", "abc2.jpg", "abc10", "abc10.jpg", "img1.png", "img2.png", "img10.png", "img12.png", "img101.png", "img101a.png"]
The above is the detailed content of How do you sort an array with elements containing both strings and numbers in a natural order, like 'img12.png' and 'img10.png'?. For more information, please follow other related articles on the PHP Chinese website!