gunjack12
gunjack12

Reputation: 267

Sort strings by last letter (Alphabetically) in JavaScript

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 / compare function?

Upvotes: 0

Views: 7133

Answers (4)

Richard Hamilton
Richard Hamilton

Reputation: 26434

It'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));
}

Upvotes: 4

tragle
tragle

Reputation: 121

Since "a" < "b", you can make a compare 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 comparator can be used on Arrays, too:

var nums = [[0,1,2], [0,1,1]];
nums.sort(endComparator); // [[0,1,1], [0,1,2]]

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

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)

Upvotes: 1

keaplogik
keaplogik

Reputation: 2409

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;
    }
});

Upvotes: 0

Related Questions