What you want to do is some sort of grouping followed by reduce. es6 does not provide groupBy
function out of the box. But you can use reduce
to achieve the same behavior.
Steps
Source Array --> Group By Person --> Join the institution names
Implemented Solution
In your case:
const arr = [{first_name: "john", age: "30", institution: {id: 1, name: "inst1"}},
{first_name: "john", age: "30", institution: {id: 2, name: "inst2"}},
{first_name: "john", age: "30", institution: {id: 3, name: "inst3"}}];
const result = arr.reduce((ac, person) => {
// check for the existing person in the accumulator
const existingRecord = ac.find(existingPerson => existingPerson.first_name === person.first_name)
// if. exists, concatenate the institution
if (existingRecord) {
existingRecord.institution += `, ${person.institution.name}`;
return ac;
// otherwise, add this as a new person
} else {
return [...ac, {
first_name: person.first_name,
age: person.age,
institution: person.institution.name
}]
}
}, []);
More general approach to implement a group by:
Most efficient method to groupby on an array of objects
You can also use Lodash which provides more options