![]()
To define a function to sort an Array with String entries, another technique is available. Array entries need to be compared.
For example, to sort the following Array by the last letter of the name, we previously used the numerical sort:
var names =["Jennifer","John","Ann","Michael","Roger"]
function lastLetterInName2(a,b){
if(a.charAt(a.length-1)<b.charAt(b.length-1)){return -1};
if(a.charAt(a.length-1)>b.charAt(b.length-1)){return 1};
return 0;
}
names.sort(lastLetterInName2);
|
var fullNames = ["Jennifer Smith",null,"John Jones","Ann","Bob","Michael White",22,"Roger Miller"]
Notice "Ann" and "Bob" have no last name, "null" is placed last in the Array. 22 (a Number) is converted to a String. a+="";b+="";
function lastName(a,b){
a+="";b+="";
A=a.charAt(a.indexOf(" ")+1);
B=b.charAt(b.indexOf(" ")+1);
return A>B?1:A<B?-1:0;
}
fullNames.sort(lastName)