You don't need lodash, or any other library, you can do this with TS. Loop over the array and assign to a new object, before returning.
grouped: { age: number, names: string[] }[] = [];
this.persons.forEach((person: Person) => {
const groupIndex = this.grouped.findIndex((item: { age: number, names: string[] }) => {
return item.age === person.age; });
groupIndex !== -1 ? this.grouped[groupIndex].names.push(person.name)
: this.grouped.push({age: person.age, names: [person.name]});
});
Then your array is available from this.grouped
.
I would define an interface for the final objects to tidy it up and make it more succinct:
export interface NamesByAge {
age?: number;
names?: string[];
}
So the final code becomes:
grouped: NamesByAge[] = [];
this.persons.forEach((person: Person) => {
const groupIndex = this.grouped.findIndex((item: NamesByAge) => {
return item.age === person.age; });
groupIndex !== -1 ? this.grouped[groupIndex].names.push(person.name)
: this.grouped.push({age: person.age, names: [person.name]});
});
Granted, it's a bit wordy, but you can obviously shorten the variable names, and if you'd prefer an if
rather than ternary, but if you don't want to include a library for this, it works :) Better still, as a function:
sortByKey(array: any[], sort: string, collectionKey: string, collectionName: string) {
const grouped: any[] = [];
array.forEach((p: any) => {
const gId = grouped.findIndex((i: any) => {
return i[sort] === p[sort];
});
if (gId !== -1) {
grouped[gId][collectionName].push(p[collectionKey]);
} else {
const obj: {} = {};
obj[sort] = p[sort];
obj[collectionName] = [p[collectionKey]];
grouped.push(obj);
}
});
return grouped;
sorted = this.sortByKey(this.persons, 'age', 'name', 'names');