Grouping names based on first letter in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ] }
]
raja
Published on 10-Oct-2020 11:34:00
Advertisements