Home > OS >  How can I group an array of objects by key using node typescript?
How can I group an array of objects by key using node typescript?

Time:01-14

const cars = [ { 'make': 'audi', 'model': 'r8', 'year': '2012' },{ 'make': 'kia', 'model': 'optima', 'year': '2013' }, ];

const details = [ { 'make': 'audi', 'owner': 'user1', 'features': 'abc' },{ 'make': 'audi', 'owner': 'user2', 'features': 'xyz' }, { 'make': 'kia', 'owner': 'user3', 'features': 'xyz' }, { 'make': 'kia', 'owner': 'user4', 'features': 'xyz' }, ];

const result = [ { 'make': 'audi', 'model': 'r8', 'year': '2012', "Details": [ { 'make': 'audi', 'owner': 'user1', 'features': 'abc' },{ 'make': 'audi', 'owner': 'user2', 'features': 'xyz' } ] }, { 'make': 'kia', 'model': 'optima', 'year': '2013', "Details": [ { 'make': 'kia', 'owner': 'user3', 'features': 'xyz' }, { 'make': 'kia', 'owner': 'user4', 'features': 'xyz' }, ] },

];

CodePudding user response:

The idea is to first group details array into a collection of make -> [detail]. Time complexity is O(n), and space complexity is also O(n) since we creating a new collection.

After that we can merge the new collection into cars array under the assumption that each make appears only once in the cars array (if not we will need a middleware step). Here time complexity is also O(n)

// group details collection
const groupDetails = details.reduce((m, detail) => {
    const items = m.get(detail.make) || [];
    m.set(detail.make, [ ...items, ...[detail] ]);
    return m;
}, new Map<string, unknown[]>());

// merge new collection into cars array
const carsDetails = cars.map(car => {
    const details = groupDetails.get(car.make) || [];
    return { ...car, ...{ Details: details }};
});

See running code example in Typescript playground

  • Related