So I have an array of objects like so:
[
{
name: "Joe Smith",
job: "Custodian",
age: 35,
id: "3421"
},
{
n
By using reduce to iterate through the array to build a new one, and simply check if the id is already inserted then concatenate the job otherwise insert the new object:
const arr = [
{ name: "Joe Smith", job: "Janitor", age: 35, id: "3421" },
{ name: "George Henderson", job: "CEO", age: 43, id: "5098" },
{ name: "Joe Smith", job: "Cook", age: 35, id: "3421" },
{ name: "Sam Doe", job: "Technician", age: 22, id: "1538" },
{ name: "Joe Smith", job: "Dishwasher", age: 35, id: "3421" }
]
const result = arr.reduce((acc, cur) => {
const duplicate = acc.find(e => e.id == cur.id)
if (duplicate) {
duplicate.job += ', ' + cur.job
} else {
acc.push(cur)
}
return acc
}, [])
console.log(result)