Given an array of strings
var lastLetterSort = [ 'blue', 'red', 'green' ];
How would you sort the strings in alphabetical order using using their last letter, ideally with a sort function / pare function?
Given an array of strings
var lastLetterSort = [ 'blue', 'red', 'green' ];
How would you sort the strings in alphabetical order using using their last letter, ideally with a sort function / pare function?
Share Improve this question edited Jan 25, 2017 at 21:14 Richard Hamilton 26.5k11 gold badges65 silver badges88 bronze badges asked Sep 10, 2015 at 1:49 gunjack12gunjack12 2673 silver badges6 bronze badges 1- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Jan Commented Sep 10, 2015 at 1:57
4 Answers
Reset to default 4It's easier to just use the charCodeAt
property, which returns a number associated with a character. Letters that occur later in the alphabet tend to have a higher value
function last(x){
return x.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
}
Try like this
var lastLetterSort = ['blue', 'red', 'green', 'aa'];
var sorted = lastLetterSort.sort(function(a, b) {
if (a[a.length - 1] > b[b.length - 1])
return 1;
else if (a[a.length - 1] < b[b.length - 1])
return -1;
return 0;
})
console.log(sorted)
lastLetterSort.sort(function(a, b){
var lastA = a.charAt(a.length - 1);
var lastB = b.charAt(b.length - 1);
if (lastA > lastB) {
return 1;
} else if (lastA < lastB) {
return -1;
} else {
return 0;
}
});
Since "a" < "b", you can make a pare function and pass it to Array.sort().
var colors = ["blue", "red", "green"];
function endComparator(a,b) {
if (a.slice(-1) < b.slice(-1)) return -1;
if (a.slice(-1) > b.slice(-1)) return 1;
return 0;
}
colors.sort(endComparator); // ["red", "blue", "green"]
Using slice() means the parator can be used on Arrays, too:
var nums = [[0,1,2], [0,1,1]];
nums.sort(endComparator); // [[0,1,1], [0,1,2]]