Skip to content
Advertisement

Render a list of names alphabetically and grouped by their first char

I need to render a list of names alphabetically and grouped by the starting letter of each name. It should look like this:

**A**

Anders
Anton
Angela

**B**

Brian
Bernard

**C**

Carl

My current solution can sort all the names that is contained within an object, but I am having trouble adding the starting letter as an element before the names (e.g. rendering ‘A’ above ‘Anders’ and ‘B’ above ‘Brian’)

Current solution:

completeEmpList = empList
  .sort((a, b) => a.Name.localeCompare(b.Name))
    .map((emp) => (
      <div> {emp.Name} </div>
    ))

It is not supposed to handle data of more than a max of 300 elements, so optimization is not that important in this case.

Advertisement

Answer

With a bit of guidance from the comments, I made it work with this code:

let previousChar = ''

if (empList) {
  completeEmpList = empList
    .sort((a, b) => a.Name.localeCompare(b.Name))
    .map((emp) => {
      if (emp.Name.charAt(0) !== previousChar) {
        previousChar = emp.Name.charAt(0)
        return (
            <div>
              <div className='charElement' key={'c' + emp.Id}> emp.Name.charAt(0)}</div>
            </div>
            <div>
              <div className='empName'>{emp.Name}</div>
            </div>
        )
      } else {
        return (
          <div className='empName'>{emp.Name}</div>
        )
      }
    })
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement