sorting - How can I force certain strings to be sorted last in javascript? -



sorting - How can I force certain strings to be sorted last in javascript? -

i'm trying sort array of strings alphabetically, except strings (e.g. "na" , "wild") should placed last. sorting priority should sorted_values_alphabetically < "na" < "wild".

if have next array:

["wild", "sit", "ipsum", "dolor", "na", "amet", "lorem"];

i sorted as:

["amet", "dolor", "ipsum", "lorem", "sit", "na", "wild"];

i thinking like

arr.sort(function(a,b) { var aval = a, bval = b; // hack create values < "na" < "wild" if (aval == "na") aval = "zzz" + aval; if (bval == "na") bval = "zzz" + bval; if (aval == "wild") aval = "zzzz" + aval; if (bval == "wild") bval = "zzzz" + bval; homecoming aval.tolowercase().localecompare(bval.tolowercase()); });

but wouldn't work unicode characters.

i'm interested in performant algorithms!

performance

just fyi, t. j. crowder's algorithm more performant via jsperf. altohugh prefer halcyon's more concise approach!

you can add together exception sorting function. little clever math got:

arr.sort(function(a,b) { var exceptions = [ "na", "wild" ], indexa, indexb; indexa = exceptions.indexof(a); indexb = exceptions.indexof(b); if (indexa === -1 && indexb === -1) { homecoming a.tolowercase().localecompare(b.tolowercase()); // regular case } homecoming indexa - indexb; // index -1 (doesn't occur), 0 or 1 });

javascript sorting

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -