Sort alphabetically with end characters

I need to sort the list in angular, in alphabetical order (ascending), but you need special characters if there is any prefix for the item that will be clicked at the end of the list. For example, for example, the list should look like this:

Apple Banana *Apple 

Any recommendations would be recommended.

+5
source share
4 answers

Here's a pretty simple solution. If you manually compare strings, it is recommended to use localeCompare , which will be correctly sorted, even if the language corresponding to the user's language dictates a different sort order. But this function alone will not solve our problem. Based on @wZVanG's clever answer, we will replace any character without words using the \W regex character group at the beginning of the line with the letter z , which automatically sorts them to the end of the list.

Please note that one of the drawbacks is that if any of your words starts with more than one z , they will be sorted after special characters. A simple workaround is to add more than z 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')); }); 
+2
source

This is probably not correct, but it is 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); 
+2
source
 var list = ["Apple","Orange", "Banana", "*Banana","*Apple"]; regex= /^[Az]+$/; 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)); 
+1
source

One line:

 var sorted = ["Banana", "Apple", "*Canana", "Blackberry", "/Banana", "*Banana", "*Apple"] .sort(function(a, b, r){ return r = /^[az]/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 start with a letter of the alphabet.

+1
source

All Articles