Home > Software engineering >  Sort array by last name
Sort array by last name

Time:09-16

Hi I have an array or users and courses.

I need to sort by the users last name, however i can't seem to figure it out what I need to do to split the name.

Below is what I have that currently only sorts by first name.

const userarray = [
    { course: "Math", user: "Steve Lewis" },
    { course: "English", user: "James Rollo" },
    { course: "IT", user: "Suzanne Collins" }
]

userarray.sort(function(a, b) {
    return a.user.toLowerCase().localeCompare(
        b.user.toLowerCase()
    );
});

console.log(userarray);

CodePudding user response:

You will have to split the name using space to get words. Assuming last word will be the last name, you can get it using pop() and use it for sorting

const userarray = [{course: "Math",user: "Steve Lewis"},{course: "English",user: "James Rollo"},{course: "IT",user: "Suzanne Collins"}]

const getLastName = (name) => name.split(' ').pop().toLowerCase()
userarray.sort(function(a, b) {
  const lnameA = getLastName(a.user)
  const lnameB = getLastName(b.user)
  return lnameA.localeCompare(lnameB);
});

console.log(userarray);

To print in the way you need, you can use following code:

const userarray = [{course: "Math",user: "Steve Lewis"},{course: "English",user: "James Rollo"},{course: "IT",user: "Suzanne Collins"}]

const getLastName = (name) => name.split(' ').pop().toLowerCase()
userarray.sort(function(a, b) {
  const lnameA = getLastName(a.user)
  const lnameB = getLastName(b.user)
  return lnameA.localeCompare(lnameB);
});

console.log(userarray.map(({
  user,
  course
}) => `${user} is studying ${course}`));


As rightly commented by gog

how are you going to sort this one: {user:"Steve Lewis" },{user:"Alice Lewis" } ?

Adding fallback to sort first name as well

const userarray = [{course: "Math",user: "Steve Lewis"},{course: "English",user: "James Rollo"},{course: "IT",user: "Suzanne Collins"}, {course: "Math",user: "Alice Lewis"}]

const getNames = (name) => {
  const names = name.split(' ');
  const lname = names.pop();
  return [names.join(' '), lname].map((name) => name.toLowerCase())
}
userarray.sort(function(a, b) {
  const [fnameA, lnameA] = getNames(a.user)
  const [fnameB, lnameB] = getNames(b.user)
  return lnameA.localeCompare(lnameB) || fnameA.localeCompare(fnameB);
});

console.log(userarray);

CodePudding user response:

You can use split to get the first name

const userarray = [
    { course: "Math", user: "Steve Lewis" },
    { course: "English", user: "James Rollo" },
    { course: "IT", user: "Suzanne Collins" }
]

userarray.sort(function(a, b) {
    var aname = a.user.split(" ").pop();
    var bname = b.user.split(" ").pop();
    return aname.toLowerCase().localeCompare(
        bname.toLowerCase()
    );
});

console.log(userarray);

  • Related