Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  119] [ 2]  / answers: 1 / hits: 43278  / 11 Years ago, mon, march 18, 2013, 12:00:00

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.


More From » jquery

 Answers
8

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

[#79521] Saturday, March 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
desiraeleandrah

Total Points: 202
Total Questions: 111
Total Answers: 115

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
desiraeleandrah questions
Thu, Nov 19, 20, 00:00, 4 Years ago
Wed, Nov 11, 20, 00:00, 4 Years ago
Wed, Oct 14, 20, 00:00, 4 Years ago
;