Sort Array Elements (string with numbers), natural sort

sort array of string numbers javascript
sort string with numbers javascript
localecompare
javascript natural sort array of objects
sort alphanumeric string in javascript
lodash alphanumeric sort
javascript sort array of numbers
javascript sort array of objects by string property

I have an array like;

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

And need to sort it so it appears like;

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

I have tried a sort function;

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

but this gives the order

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

I have tried to think of a regex that will work but can't get my head around it. If it helps the format will always be 2 letters, x amount of numbers, then any number of characters.


This is called "natural sort" and can be implemented in JS like this:

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;
}

/////////////////////////

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));

The better way to do natural sort in JavaScript, We can sort strings and numbers differently. Unless your array has numbers or strings containing numbers in it. 1 2 3 To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.


Natural Sorting in JavaScript - My Adventures, This type of sort treats embedded numbers as numbers, leading to a more human -friendly ordering of string values. This dovetails perfectly with the Array. prototype.sort() method, which uses exactly these types of ranges to� If A is a multidimensional array, then sort (A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. B = sort (A,dim) returns the sorted elements of A along dimension dim . For example, if A is a matrix, then sort (A,2) sorts the elements of each row.


var re = /([a-z]+)(\d+)(.+)/i;
var arr = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
var order = arr.sort( function(a,b){
    var ma = a.match(re),
        mb = b.match(re),
        a_str = ma[1],
        b_str = mb[1],
        a_num = parseInt(ma[2],10),
        b_num = parseInt(mb[2],10),
        a_rem = ma[3],
        b_rem = mb[3];
    return a_str > b_str ? 1 : a_str < b_str ? -1 : a_num > b_num ? 1 : a_num < b_num ? -1 : a_rem > b_rem;  
});

Using The String localeCompare() Method To Implement A Natural , If omitted, the array elements are converted to strings, then sorted according In a numeric sort, 9 comes before 80, but because numbers are� Applied from SO: Sort Array Elements (string with numbers), natural sort. You need a natural sort. A good generic natural sort providing the comparison to sort that will also work in case the strings also contain letters:


I liked georg's solution a lot, but I needed underscores ("_") to sort before numbers. Here's how I modified his code:

var chunkRgx = /(_+)|([0-9]+)|([^0-9_]+)/g;
function naturalCompare(a, b) {
    var ax = [], bx = [];
    
    a.replace(chunkRgx, function(_, $1, $2, $3) {
        ax.push([$1 || "0", $2 || Infinity, $3 || ""])
    });
    b.replace(chunkRgx, function(_, $1, $2, $3) {
        bx.push([$1 || "0", $2 || Infinity, $3 || ""])
    });
    
    while(ax.length && bx.length) {
        var an = ax.shift();
        var bn = bx.shift();
        var nn = an[0].localeCompare(bn[0]) || 
                 (an[1] - bn[1]) || 
                 an[2].localeCompare(bn[2]);
        if(nn) return nn;
    }
    
    return ax.length - bx.length;
}

/////////////////////////

test = [
    "img12.png",
    "img10.png",
    "img2.png",
    "img1.png",
    "img101.png",
    "img101a.png",
    "abc10.jpg",
    "abc10",
    "abc2.jpg",
    "20.jpg",
    "20",
    "abc",
    "abc2",
    "_abc",
    "_ab_c",
    "_ab__c",
    "_abc_d",
    "ab_",
    "abc_",
    "_ab_cd",
    ""
];

test.sort(naturalCompare)
document.write("<pre>" + JSON.stringify(test,0,3));

Array.prototype.sort(), Natural order sorting sorts strings containing digits in a way such that the numerical value of the eFKa, sort_nat requires a cell array of strings. I wan to use this program to sort a vector a strings which have numerical values in their name. Sort an Array which contain 1 to N values in O(N) using Cycle Sort; Minimum increment or decrement required to sort the array | Top-down Approach; Sort the strings based on the numbers of matchsticks required to represent them; Check if the given string is shuffled substring of another string; Sort an array of Strings according frequency


Pad numbers in string with leading zeros, then sort normally.

var naturalSort = function (a, b) {
    a = ('' + a).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
    b = ('' + b).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
    return a.localeCompare(b);
}

var naturalSortModern = function (a, b) {
    return ('' + a).localeCompare(('' + b), 'en', { numeric: true });
}

console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSort)));

console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSortModern)));

sort_nat: Natural Order Sort - File Exchange, I need to sort strings containing numbers. "A200", "A20"]; julia> @btime naturalsort($l) 10.196 μs (233 allocations: 6.67 KiB) 5-element Array{String,1}: " A5a" "A10a" "A10b" "A20" "A200" -v natural sort of (version) numbers within text . 1 Like. When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'}); var myArray = ['1_Document', '11_Document', '2_Document']; console.log(myArray.sort(collator.compare));


Sorting strings containing numbers, so that "A2" < "A10"?, Different Approaches to Sorting Elements of an ArrayList in Java Consider an The sort order can be either alphabetic or numeric, and either ascending (up) or� To perform bubble sort in C programming, you have to ask from user to enter the array size and then array elements, now start sorting the array elements using bubble sort technique. Logic Used in Bubble Sort The logic used in bubble sort is that each adjacent element is compared.


Program to sort a string in alphabetical order in java, Sort an array: <?php The natsort() function sorts an array by using a "natural order" algorithm. The values keep their original keys. PHP Changelog: PHP 5.2 .1: Zero padded numeric strings (e.g., '00006') now ignore the 0 padding� In sort elements by frequency of occurrences problem, we have given an array a[]. Sort array elements in such a way that the element with the highest number of occurrences comes first. If the number of occurrences is equal then the print the number which appeared first in the array.


PHP natsort() Function, Let's start by sorting integer arrays first using Arrays.sort() method. Collections. sort(entries, new Comparator<Entry<Integer, String>>() { The natural order in java means an order in which primitive or Object should be� The sort () method allows you to sort elements of an array in place. Besides returning the sorted array, the sort () method changes the positions of the elements in the original array. By default, the sort () method sorts the array elements in ascending order with the smallest value first and largest value last.