So I have an array of objects like so:
[
{
name: "Joe Smith",
job: "Custodian",
age: 35,
id: "3421"
},
{
n
I would suggest using a temporary Map
, so to avoid having to iterate each time to find whether the name is a duplicate (like with find
).
Also, it seems better practice to let the multiple values of job
be put in an array:
let data = [{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"}];
let map = new Map(data.map(({name, job, age, id}) => [id, { name, job: [], age, id}]));
data.forEach(o => map.get(o.id).job.push(o.job));
let result = Array.from(map.values());
console.log(result);
If you really want to join the job arrays as comma separated values, then apply join(", ")
on them, but I would go for the array.