LearnFrenzy
Sign in Take a free test

Array Methods · Array Methods Coding Problems · Question 9

Group words by their first letter in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Group city names by their first letter (case-insensitive), sort each group, and print the groups in alphabetical order.

Solution
main.js
const cities = ["pune", "Patna", "Delhi", "Bengaluru", "durgapur", "Bhopal", "Agra"];

const groups = cities.reduce((acc, city) => {
  const letter = city[0].toUpperCase();
  (acc[letter] ??= []).push(city[0].toUpperCase() + city.slice(1));
  return acc;
}, {});

for (const letter of Object.keys(groups).sort()) {
  console.log(`${letter}: ${groups[letter].sort().join(", ")}`);
}

Output Verified by running it on Node.js

A: Agra
B: Bengaluru, Bhopal
D: Delhi, Durgapur
P: Patna, Pune

reduce builds an object of arrays keyed by letter (??= creates each array once). Names are capitalised so that sorting is consistent, and the keys are sorted for the output.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links