Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array Elements (string with numbers), natural sort

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.

like image 273
Rooneyl Avatar asked Mar 18 '13 14:03

Rooneyl


People also ask

How do you sort a number in an array of strings?

Using the Arrays.util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything.

Can JavaScript sort string containing numbers?

Voted Best Answer You should be using the JavaScript array object's sort method. If you are going to sort strings that consist of letters and numbers you may need to pad some numbers with leading zeros so the numeric portion of the string is the same length for all members.

How do I sort string numbers in TypeScript?

Use the sort() method to sort an array in TypeScript, e.g. numArray. sort((a, b) => a - b) . The sort method takes a function that defines the sort order as a parameter. The function has to be provided when sorting a numeric array, but is optional when sorting string arrays.

How do I sort numbers in a string?

Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.


1 Answers

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

To sort in reverse order, just swap the arguments:

test.sort(function(a, b) { return naturalCompare(b, a) }) 

or simply

test = test.sort(naturalCompare).reverse(); 
like image 195
georg Avatar answered Sep 18 '22 22:09

georg