Sort and group objects alphabetically by the first letter from an array in JavaScript

Today we’ll explain to you how to sort and group objects alphabetically by the first letter from an array in JavaScript.

Sometimes, we need to display the data in the group alphabetical order for example A to Z listing and the grouping should be managed by the first letter of the value of one of the properties.

Let’s consider the below array for the example.

Steps to sort and group objects alphabetically by first letter

  1. Sort an array
  2. Group objects alphabetically by first letter
  3. Output

1. Sort an array

Here in the first step, we have to sort an array in alphabetical order based on the employee’s name.

Use the below sort method to sort an array by employee’s name.

Refer to this link for more information about the localeCompare.

After running the above command, the value of the employees variable should look like below.

2. Group objects alphabetically by first letter

Now in the second step, we will split an array into a small group of the array alphabetically by the first letter that returns an object with A, B, C keys with children as values.

Use the below code to get the final result.

Here we have used the reduce method. Check out the below link for more information.

Map, Filter and Reduce Operators in JavaScript

3. Output

Run the above code and check out the below output.

That’s it for today.
Thank you for reading. Happy Coding..!!

You may also like...

Leave a Reply

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