Home > Web Front-end > JS Tutorial > How do you sort an array with elements containing both strings and numbers in a natural order, like 'img12.png' and 'img10.png'?

How do you sort an array with elements containing both strings and numbers in a natural order, like 'img12.png' and 'img10.png'?

Mary-Kate Olsen
Release: 2024-12-16 15:53:17
Original
948 people have browsed it

How do you sort an array with elements containing both strings and numbers in a natural order, like

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"]
Copy after login

To achieve the desired sorting:

["IL0 Foo", "IL3 Bob says hello", "IL10 Baz", "PI0 Bar"]
Copy after login

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;
}
Copy after login

Explanation

  • The function replaces any digits or non-digits with an array of subarrays.
  • The elements of each subarray represent the numeric and textual components of the corresponding substring.
  • The function iterates through the subarrays of both strings, comparing numeric values first and then textual values.
  • If a numeric comparison is inconclusive, the function performs a lexicographic comparison of the textual components.
  • The spread between the lengths of the remaining subarrays for each string determines the natural ordering.

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)
Copy after login

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"]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template