I want to write unique initials before listing an array of names, so given const names = ["Bill", "Jack", "john"], I would like to print something like:
<ul>
<li>B
<ul>
<li>Bill</li>
</ul>
</li>
<li>J
<ul>
<li>John</li>
<li>jack</li>
</ul>
</li>
</ul>
The way I found to do this is to push the JSX into an array before rendering it like:
const RenderNames = () => {
let initials = [];
let renderData = [];
names.forEach(name => {
let initial = name.charAt(0).toUpperCase();
if(initials.indexOf(initial) === -1){
initials.push(initial)
renderData.push(<li>{initial}</li>)
}
renderData.push(<li>{name}</li>)
});
return <ul>{renderData}</ul>;
}
But I feel the code is a bit clunky, and I can only push in tags that are immediately closing. Is this the best way to do things or could it be done better?