Code Premix

Grouping array of object based on first letter in JavaScript

📅August 16, 2021
🗁JavaScript

Today we’ll explain to you how to sort and group an array of object based on first letter 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.

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" }
];

  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.

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.

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.

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 in JavaScript

3. Output

Run the above code and check out the below output.

[
  {
    "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" }
    ]
  }
]

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!