Grouping names based on first letter in JavaScript


Suppose, we have an array of names like this −

const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];

We are required to write a JavaScript function that takes in one such array. The function should return an array of objects with two properties −

  • letter -> the letter on which the names are grouped

  • names -> an array of names that falls in that group

Example

The code for this will be −

const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
const groupNames = arr => {
   const map = arr.reduce((acc, val) => {
      let char = val.charAt(0).toUpperCase();
      acc[char] = [].concat((acc[char] || []), val);
      return acc;
   }, {});
   const res = Object.keys(map).map(el => ({
      letter: el,
      names: map[el]
   }));
   return res;
};
console.log(groupNames(arr));

Output

The output in the console −

[
   { letter: 'S', names: [ 'Simon', 'Susi' ] },
   { letter: 'M', names: [ 'Mike' ] },
   { letter: 'J', names: [ 'Jake', 'James' ] },
   { letter: 'L', names: [ 'Lara' ] },
   { letter: 'B', names: [ 'Blake' ] }
]

Updated on: 10-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements