sort an array by last name in javascript

To sort an array of objects by the last name property, you can use a comparator function with the Array.sort() method.

The comparator function takes two parameters, which represent the current and next items in the array being compared. Within the comparator function, you can access the last name property of each item by splitting the full name string by whitespace and selecting the last item in the resulting array.

index.tsx
const people = [
  { fullName: "John Smith" },
  { fullName: "Adam Johnson" },
  { fullName: "Sarah Lee" },
  { fullName: "Emma Black" }
]

people.sort((a, b) => {
  const aLastName = a.fullName.split(' ')[1];
  const bLastName = b.fullName.split(' ')[1];
  return aLastName.localeCompare(bLastName);
});

console.log(people);
// Output: [{ fullName: "Emma Black" }, { fullName: "Adam Johnson" }, { fullName: "Sarah Lee" }, { fullName: "John Smith" }]
452 chars
16 lines

In this example, the array of people is sorted by the last name of each person using the Array.sort() method and a comparator function. The localeCompare() method is used to determine the correct order of the items based on each last name.

gistlibby LogSnag