Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array sort by last name, first name

I have the following array in JavaScript, I need to sort them by last name.

var names = [Jenny Craig, John H Newman, Kelly Young, Bob];

Results would be:

Bob, 
Jenny Craig, 
John H Newman, 
Kelly Young 

Any examples on how to do this?

like image 435
Jeffrey Messick Avatar asked Jun 11 '14 21:06

Jeffrey Messick


2 Answers

Try this:

const names = ["John H Newman", "BJenny Craig", "BJenny Craig", "Bob", "AJenny Craig"];

const compareStrings = (a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;

  return 0;
}

const compare = (a, b) => {
  const splitA = a.split(" ");
  const splitB = b.split(" ");
  const lastA = splitA[splitA.length - 1];
  const lastB = splitB[splitB.length - 1];

  return lastA === lastB ?
    compareStrings(splitA[0], splitB[0]) :
    compareStrings(lastA, lastB);
}

console.log(names.sort(compare));
like image 109
Amir Popovich Avatar answered Nov 19 '22 04:11

Amir Popovich


function lastNameSort(a,b) {
    return a.split(" ").pop()[0] > b.split(" ").pop()[0]
};
names.sort(lastNameSort);

This was inspired by this answer.

like image 43
Samba Avatar answered Nov 19 '22 05:11

Samba