close

How to group an array of objects by key

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to group an array of objects by key in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to group an array of objects by key ?

  1. How to group an array of objects by key ?

    to group an array of objects by key Just try this one it works fine for me.
    let grouped = _.groupBy(cars, 'make');
    Note: Using lodash lib, so include it.

  2. How to group an array of objects by key ?

    to group an array of objects by key Just try this one it works fine for me.
    let grouped = _.groupBy(cars, 'make');
    Note: Using lodash lib, so include it.

Method 1


Its also possible with a simple for loop:

 const result = {};

 for(const {make, model, year} of cars) {
   if(!result[make]) result[make] = [];
   result[make].push({ model, year });
 }

Method 2

Just try this one it works fine for me.

let grouped = _.groupBy(cars, 'make');

Note: Using lodash lib, so include it.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment