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.
1 2 3 4 5 6 7 8 9 | let employees = [ { name: "Brianna", age: "25" }, { name: "Axle", age: "29" }, { name: "David", age: "22" }, { name: "Brooklyn", age: "23" }, { name: "Camila", age: "24" }, { name: "Abigail", age: "25" }, { name: "Charlotte", age: "28" } ]; |
Steps to sort and group objects alphabetically by first letter
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.
1 | employees.sort((a, b) => a.name.localeCompare(b.name, 'es', { sensitivity: 'base' })) |
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.
1 2 3 4 5 6 7 8 9 | let employees = [ { name: "Abigail", age: "25" }, { name: "Axle", age: "29" }, { name: "Brianna", age: "25" }, { name: "Brooklyn", age: "23" }, { name: "Camila", age: "24" }, { name: "Charlotte", age: "28" }, { name: "David", age: "22" } ]; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let data = employees.reduce((r, e) => { // get first letter of name of current element let alphabet = e.name[0]; // if there is no property in accumulator with this letter create it if (!r[alphabet]) r[alphabet] = { alphabet, record: [e] } // if there is push current element to children array for that letter else r[alphabet].record.push(e); // return accumulator return r; }, {}); let result = Object.values(data); console.log(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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | [ { "alphabet": "A", "record": [ { "name": "Abigail", "age": "25" }, { "name": "Axle", "age": "29" } ] }, { "alphabet": "B", "record": [ { "name": "Brianna", "age": "25" }, { "name": "Brooklyn", "age": "23" } ] }, { "alphabet": "C", "record": [ { "name": "Camila", "age": "24" }, { "name": "Charlotte", "age": "28" } ] }, { "alphabet": "D", "record": [ { "name": "David", "age": "22" } ] } ] |
That’s it for today.
Thank you for reading. Happy Coding..!!