Grouping An Array Of Objects By Key
JavaScript
12/01/2023
Imagine the following dataset which we would like to group by type
.
JAVASCRIPT
const food = [ { type: "vegetable", name: "Spinach" }, { type: "fruit", name: "Pear" }, { type: "fruit", name: "Apple" }, { type: "vegetable", name: "Carrot" }, { type: "vegetable", name: "Broccoli" },]
There are 2 ways to solve this task, either by using plain JavaScript or Lodash.
Plain JavaScript
The cleanest way to solve this problem with plain JavaScript is by using a reducer.
JAVASCRIPT
const foodTypes = food.reduce( (accumulator, food) => { // Retrieve any existing values that have already been categorized by `type`. // If none exist, start with an empty array. const existingValues = accumulator[food.type] || [] // Assign the new `food` value and any existing values to their respective `type`. accumulator[food.type] = [food, ...existingValues] return accumulator }, // Start with an empty object. {})
console.log(foodTypes)// Object { vegetable: (3) […], fruit: (2) […] }
Using Lodash
Lodash provides a much more straightforward approach as the implementation details are hidden by the library.
JAVASCRIPT
const foodTypes = _.groupBy(food, food => food.type)// Or _.groupBy(food, 'type')
console.log(foodTypes)// Object { vegetable: (3) […], fruit: (2) […] }
Note that in the second argument of groupBy
, you specify the property you wish to group by, either by passing a callback function or the property name as a string.