So, I am trying to make the UI as follows:

And I have an array of users
[{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}]
What I'm trying to do is sort the array by the first letter of the name property and add a header object in front of each. For example, in the picture you can see the letters A, B, I and J as headings.
Now I started working as follows:
let final = []
const sortedUsers = state.test_list.sort((a, b) => a.name.localeCompare(b.name))
for (let x = 0; x < sortedUsers.length; x++) {
const user = sortedUsers[x].name
if (user.charAt(0) === 'A') {
const checkIfExists = final.findIndex((f) => f.header === 'A')
if (checkIfExists < 0) final.push({header: 'A'})
}
else if (user.charAt(0) === 'B') {
const checkIfExists = final.findIndex((f) => f.header === 'B')
if (checkIfExists < 0) final.push({header: 'B'})
}
final.push(user)
}
and if I write the final array, I get:

what is right.
My concern is that the code is very long, and I have no idea whether it is possible to optimize or reduce the code.
Is there any other way to do something like this? Any help would be greatly appreciated.
source
share