I need to render a list of names alphabetically and grouped by the starting letter of each name. It should look like this:
JavaScript
x
15
15
1
**A**
2
3
Anders
4
Anton
5
Angela
6
7
**B**
8
9
Brian
10
Bernard
11
12
**C**
13
14
Carl
15
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:
JavaScript
1
6
1
completeEmpList = empList
2
.sort((a, b) => a.Name.localeCompare(b.Name))
3
.map((emp) => (
4
<div> {emp.Name} </div>
5
))
6
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:
JavaScript
1
23
23
1
let previousChar = ''
2
3
if (empList) {
4
completeEmpList = empList
5
.sort((a, b) => a.Name.localeCompare(b.Name))
6
.map((emp) => {
7
if (emp.Name.charAt(0) !== previousChar) {
8
previousChar = emp.Name.charAt(0)
9
return (
10
<div>
11
<div className='charElement' key={'c' + emp.Id}> emp.Name.charAt(0)}</div>
12
</div>
13
<div>
14
<div className='empName'>{emp.Name}</div>
15
</div>
16
)
17
} else {
18
return (
19
<div className='empName'>{emp.Name}</div>
20
)
21
}
22
})
23