• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 300
  • Last Modified:

JavaScript: Order Array by Last Name

How can I order this list by last name?

This does NOT work:

 var str = 'X. Michael Goo,Suzy M. Kat,Sal M. Haircut,Scott N. Yuu,Larry B. Huff,Geof L. Mack,David A. Xaa,Brian C. Fuu';
 var people = str.split(',');
 people = people.sort(function(a,b){return a<b;});
 alert(people.join('\n'))

Open in new window

0
hankknight
Asked:
hankknight
  • 2
2 Solutions
 
hieloCommented:
within the function, split the name in "a" and in "b" at the spaces and then compare just the last name (the last item after the split(' ')) -see code below:
 var str = 'X. Michael Goo,Suzy M. Kat,Sal M. Haircut,Scott N. Yuu,Larry B. Huff,Geof L. Mack,David A. Xaa,Brian C. Fuu';
 var people = str.split(',');
 people = people.sort(  function(a,b){
 		var last_a=a.split(' ').pop();
		var last_b=b.split(' ').pop();
		return last_a<last_b?-1:1;
		
		}  );
 alert(people.join('\n'))

Open in new window

0
 
Rainer JeschorCommented:
Here we go:
http://jsfiddle.net/EE_RainerJ/ajXyw/

Using RegEx
0
 
hieloCommented:
NOTE: On my first post, if you prefer the sort order to be in descending order then change:
return last_a<last_b?-1:1;

so that the 1 and -1 are swapped:
return last_a<last_b?1:-1;
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now