Group objects by property in JavaScript


Suppose, we have an array of objects that contains data about some fruits and vegetables like this −

const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];

We are required to write a JavaScript function that takes in one such array.

Our function should then group the array objects based on the "type" property of the objects.

It means that all the "fruit" type objects are grouped together and the "vegetable' type grouped together separately.

Example

The code for this will be −

const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];
const transformArray = (arr = []) => {
   const res = [];
   const map = {};
   let i, j, curr;
   for (i = 0, j = arr.length; i < j; i++) {
      curr = arr[i];
      if (!(curr.type in map)) {
         map[curr.type] = {type: curr.type, foods: []};
         res.push(map[curr.type]);
      };
      map[curr.type].foods.push(curr.food);
   };
   return res;
};
console.log(transformArray(arr));

Output

And the output in the console will be −

[
   { type: 'fruit', foods: [ 'apple', 'banana' ] },
   { type: 'vegetable', foods: [ 'potato' ] }
]

Updated on: 24-Nov-2020

670 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements