Giles Taylor Giles Taylor - 4 months ago 8
jQuery Question

Taking an array of full names and sorting it by surname

I want to sort an array of full names alphabetically by last name using JQuery or JavaScript but keep getting lost in loops and splits. Can anyone help?

var names = ["Adam Benson", "Clare Donaldson", "Ben Adams", "Donald Clarkson"];


Thanks and sorry for what seems like a very simple question!

Answer

Do it with help of Array#sort, String#split and String#localeComapre methods.

var names = ["Adam Benson", "Clare Donaldson", "Ben Adams", "Donald Clarkson"];

// sort  array with custom functions
names.sort(function(a, b) {
  // compare lastname part for sorting
  return a.split(' ')[1].localeCompare(b.split(' ')[1]);
})

console.log(names);

FYI : In case name contains middle name part then change name.split(' ')[1] to name.split(' ').pop() to get the last element from array(which is thw lastname).