Reputation: 205
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.
Upvotes: 6
Views: 4373
Reputation: 32076
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'));
});
Upvotes: 4
Reputation: 12014
One line:
var sorted = ["Banana", "Apple", "*Canana", "Blackberry", "/Banana", "*Banana", "*Apple"]
.sort(function(a, b, r){
return r = /^[a-z]/i, (r.test(a) ? a : "z" + a) > (r.test(b) ? b : "z" + b)
});
//Test
document.write(sorted.join("<br />"));
Add Z
if the item does not begin with a letter of the alphabet.
Upvotes: 1
Reputation: 6887
var list = ["Apple","Orange", "Banana", "*Banana","*Apple"];
regex= /^[A-z]+$/;
dummyArray1=[];
dummyArray2=[];
for(var i =0;i< list.length; i++){
if(regex.test(list[i][0])){
dummyArray1.push(list[i]);
}
else{
dummyArray2.push(list[i]);
}
}
console.log(dummyArray1.sort());
console.log(dummyArray2.sort());
console.log(dummyArray1.concat(dummyArray2));
Upvotes: 1
Reputation: 2404
This is probably not correct but its the best I can think of at this hour.
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);
Upvotes: 2