Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list alphabetically with characters at the end

I need to sort a list in angular, alphabetically(ascending) but want the special characters if any prefixed to an item to be pushed at the end of the list. For e.g: the list should like:

Apple
Banana
*Apple

any suggestions would be recommended.

like image 358
Preena Khanuja Avatar asked Aug 07 '15 03:08

Preena Khanuja


2 Answers

Here's a fairly simple solution. When manually comparing strings it's good practice to use localeCompare which will correctly sort even when the user's language specific locale dictates a different sort order. But that function alone won't solve our problem. Building on top of @wZVanG's clever answer, we'll replace any non-word characters, using the \W regex character group, at the beginning of the string with the letter z which will automatically sort them to the end of the list.

Note one flaw in this is that if any of your words start with more than one z they will get sorted after the special characters. A simple workaround is to add more zs to the string, as in return a.replace(/^\W+/, 'zzz').localeCompare(b.replace(/^\W+/, 'zzz').

var array = ["Banana", "Apple", "*Canana", "Blackberry", "Banana", "*Banana", "*Apple"];

array.sort(function(a,b) {
    return a.replace(/^\W+/, 'z').localeCompare(b.replace(/^\W+/, 'z'));
});
like image 151
Andy Ray Avatar answered Oct 26 '22 20:10

Andy Ray


This is probably not correct but its the best I can think of at this hour.

DEMO

var array = ["Apple", "Banana", "*Apple"];

// Split the arrays with and without special chars
var alphaNumeric = array.filter(function (val) {
    return !(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(val));
});
var specialChars = array.filter(function (val) {
    return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(val);
});

console.log(alphaNumeric, specialChars);

// Sort them individually
alphaNumeric.sort();
specialChars.sort();

// Bring them back together but put the special characters one afterwards
var both = alphaNumeric.concat(specialChars);

console.log(both);
like image 20
Pedro Estrada Avatar answered Oct 26 '22 19:10

Pedro Estrada