Home > Web Front-end > JS Tutorial > How do you implement a natural sort algorithm in JavaScript for arrays containing mixed alphanumeric elements?

How do you implement a natural sort algorithm in JavaScript for arrays containing mixed alphanumeric elements?

Susan Sarandon
Release: 2024-11-09 16:06:02
Original
1023 people have browsed it

How do you implement a natural sort algorithm in JavaScript for arrays containing mixed alphanumeric elements?

Natural Sorting of Array Elements with Numbers and Alphabets

Determining the order of array elements containing numerical values and alphabetical characters can be challenging. A natural sort is required to handle this scenario, which arranges elements based on their true values.

Sample Array and Desired Result

Consider the following input array:

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

The desired sorted order is:

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

Naive Sorting Approach

A simple comparison function, like the one provided, sorts the elements only according to the initial portion (2 letters) and ignores the numerical part:

function compare(a, b) {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
}
Copy after login

Natural Sort Implementation in JavaScript

To achieve a natural sort, the following function can be used:

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 splits each element into an array of pairs, where the first element is a number (or Infinity if no number) and the second element is a string:

["IL0 Foo"] -> [["0", "IL"], ["Foo", ""]]
["PI0 Bar"] -> [["0", "PI"], ["Bar", ""]]
Copy after login

The comparison logic then compares the pairs one by one, giving priority to numerical values. If the numerical values are equal, the strings are compared using localeCompare.

Example Usage and Result

Sorting the sample array using the naturalCompare function:

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 will 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 implement a natural sort algorithm in JavaScript for arrays containing mixed alphanumeric elements?. 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