Within my JavaScript code, I have an object structured as follows:
[
{
firstname: "John",
lastname: "Smith"
},
{
firstname: "Peter",
lastname: "Gregory"
},
{
firstname: "John",
lastname: "Fisher"
},
{
firstname: "Sam",
lastname: "Fisher"
}
]
My goal is to present the first names in a comma-separated string. The challenge lies in displaying the first initial of the last name only when necessary to differentiate two individuals with the same first name.
Ultimately, the output should resemble this:
John S., Peter, John F., Sam
Up until now, I've managed to create a loop that retains past initials. However, the obstacle arises with the fourth entry in the given example; an individual whose last name sets them apart from others but does not share a first name with anyone.
What would be the most efficient approach to tackle this issue?