简体   繁体   中英

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 eg: 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);
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));

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 begin with a letter of the alphabet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM