"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort Arrays with Strings Containing Numbers in Natural Order?

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

Published on 2024-12-23
Browse:279

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(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
    b.replace(/(\d )|(\D )/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
    
    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>"   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"
]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3