React: Contacts grouped by letter

Group a list before rendering it, the way phone contact lists are shown.

What to build

A contact list grouped under the first letter of each name.

Requirements

  • Keep contacts. Sort the names alphabetically, group them by first letter, and for each letter in order render a section with an h3 holding the letter and a ul of the names.
  • Use keys for the sections (the letter) and for the items (the name).

Constraints

Do not change the contacts array; work on a copy.

Example

The preview shows A with Aisha and Arif, B with Bilal, R with Rahim and Rina, and Z with Zoya.

Why it works

The data work (sorting and grouping) happens before the JSX, so the JSX only has to map over letters and then over names, and keys keep every section and item identifiable.

Hints

Hint 1

Sort a copy of the names, then build an object (or Map) from first letter to names.

Hint 2

Map over the letters to make a section each, and over each letter's names to make the items.

Solution

Show one correct solution (try it yourself first)
const contacts = ["Rina", "Arif", "Zoya", "Bilal", "Aisha", "Rahim"];

export default function App() {
  const groups = {};
  for (const name of [...contacts].sort()) {
    const letter = name[0];
    if (!groups[letter]) groups[letter] = [];
    groups[letter].push(name);
  }
  return (
    <div>
      {Object.keys(groups).map((letter) => (
        <section key={letter}>
          <h3>{letter}</h3>
          <ul>
            {groups[letter].map((name) => (
              <li key={name}>{name}</li>
            ))}
          </ul>
        </section>
      ))}
    </div>
  );
}

Lesson: Lists and keys →