Home > Web Front-end > JS Tutorial > body text

How to Sort Arrays with Strings Containing Numbers in Natural Order?

Barbara Streisand
Release: 2024-11-17 19:18:01
Original
471 people have browsed it

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

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

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

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

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

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!

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