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.
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 z
s 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'));
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With