Write a function that takes an array of strings and groups them by their first letter.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Logic/Approach:

1. Use a Map or an object to store the groups.

2. Iterate through the array of strings.

3. For each string, get its first letter (and optionally normalize it to lowercase).

4. If the first letter is not yet a key in your map/object, create a new entry with an array containing the current string.

5. If the first letter is already a key, push the current string into the existing array.

function groupByFirstLetter(strings) {
  const groups = {}; // Using a plain object

  for (const str of strings) {
    if (str.length === 0) continue;

    const firstLetter = str[0].toLowerCase();

    if (!groups[firstLetter]) {
      groups[firstLetter] = [];
    }
    groups[firstLetter].push(str);
  }
  return groups;
}

const words = ["Apple", "Banana", "Avocado", "Bear", "Cat"];
console.log(groupByFirstLetter(words));
// Output: { a: ["Apple", "Avocado"], b: ["Banana", "Bear"], c: ["Cat"] }