Convert array of arrays to array of objects grouped together JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have a two-dimensional array that contains data about some colors and fruits like this

const data = [
   ['orange', 'fruit'],
   ['red', 'color'],
   ['green', 'color'],
   ['orange', 'color'],
   ['banana', 'fruit'],
   ['blue', 'color'],
   ['lemon', 'fruit'],
   ['mango', 'fruit'],
   ['lemon', 'color'],
];

We have to write a function that takes in this array and returns an array in which the different fruits and colors are grouped by their categories.

Like in this example we only have two categories namely ‘fruit’ and ‘color’, so we should expect an array of two objects in the output like this −

[
   {
      group: 'fruit',
      value: [ 'orange', 'banana', 'lemon', 'mango' ]
   },
   {
      group: 'color',
      value: [ 'red', 'green', 'orange', 'blue', 'lemon' ]
   }
]

Note − In this very example we only have two categories but we are required to write a solution that works for a dynamic number of categories and not just only two.

So, let’s devise a solution for this problem. We will use the Array.prototype.reduce() method and for each subarray we will check if we have an existing group or not. If the group exists, we push the new value into its value property otherwise we create a new object for that group and push it into the array.

Example

const data = [
   ['orange', 'fruit'],
   ['red', 'color'],
   ['green', 'color'],
   ['orange', 'color'],
   ['banana', 'fruit'],
   ['blue', 'color'],
   ['lemon', 'fruit'],
   ['mango', 'fruit'],
   ['lemon', 'color'],
];
const groupData = arr => {
   return arr.reduce((acc, val) => {
      const [value, groupName] = val;
      const groupIndex = acc.findIndex(el => el?.group === groupName);
      if(groupIndex !== -1){
         acc[groupIndex].value.push(value);
      }else{
         acc.push({
            group: groupName,
            value: [value]
         });
      }
      return acc;
   }, []);
};
console.log(groupData(data));

Output

The output in the console will be −

[
   { group: 'fruit', value: [ 'orange', 'banana', 'lemon', 'mango' ] },
   {
      group: 'color',
      value: [ 'red', 'green', 'orange', 'blue', 'lemon' ]
   }
]
raja
Published on 25-Aug-2020 06:58:15
Advertisements