Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

JavaScript: Order Array by Last Name

Posted on 2013-06-11
Medium Priority
298 Views
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;});
``````
0
Question by:hankknight
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 82

Accepted Solution

hielo earned 1400 total points
ID: 39239217
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;

}  );
``````
0

LVL 44

Assisted Solution

Rainer Jeschor earned 600 total points
ID: 39239268
Here we go:
http://jsfiddle.net/EE_RainerJ/ajXyw/

Using RegEx
0

LVL 82

Expert Comment

ID: 39239289
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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month9 days, 16 hours left to enroll