Sort Array by Firstname (Alphabetically) in Javascript

Sorting an Array by First Name (Alphabetically) in JavaScript

When working with arrays in JavaScript, it is often necessary to sort them in a specific order. One common requirement is to sort an array of objects by their first name in alphabetical order. In this blog post, we will explore different solutions to achieve this using JavaScript.

Solution 1: Using the sort() method with a custom compare function

The simplest way to sort an array by first name is by using the sort() method, which sorts the elements of an array in place. By providing a custom compare function, we can specify the sorting logic based on the first name property of the objects.


const people = [
  { firstName: 'John', lastName: 'Doe' },
  { firstName: 'Alice', lastName: 'Smith' },
  { firstName: 'Bob', lastName: 'Johnson' }
];

people.sort((a, b) => a.firstName.localeCompare(b.firstName));

console.log(people);

This will output:


[
  { firstName: 'Alice', lastName: 'Smith' },
  { firstName: 'Bob', lastName: 'Johnson' },
  { firstName: 'John', lastName: 'Doe' }
]

Solution 2: Using the localeCompare() method directly

If you prefer a more concise solution, you can use the localeCompare() method directly within the sort() method. This method compares two strings and returns a negative, zero, or positive value depending on the sorting order.


const people = [
  { firstName: 'John', lastName: 'Doe' },
  { firstName: 'Alice', lastName: 'Smith' },
  { firstName: 'Bob', lastName: 'Johnson' }
];

people.sort((a, b) => a.firstName.localeCompare(b.firstName));

console.log(people);

This will give the same output as the previous solution.

By using either of these solutions, you can easily sort an array of objects by their first name property in alphabetical order. Choose the solution that best fits your coding style and requirements.

Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *