Categories
JavaScript Answers

How to group an array of objects by key with JavaScript?

Spread the love

To group an array of objects by key with JavaScript, we use the Lodash groupBy method.

For instance, we write

const cars = [
  {
    make: "audi",
    model: "r8",
    year: "2012",
  },
  {
    make: "audi",
    model: "rs5",
    year: "2013",
  },
  {
    make: "ford",
    model: "mustang",
    year: "2012",
  },
  {
    make: "ford",
    model: "fusion",
    year: "2015",
  },
  {
    make: "kia",
    model: "optima",
    year: "2012",
  },
];

const grouped = _.groupBy(cars, (car) => car.make);

console.log(grouped);

to call groupBy with the cars array and a function that returns the value of the make property in each entry to return an array that’s grouped by the make property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.