Group values on same property - JavaScript


Suppose we have an array like this −

const arr = [
   {unit: 35, brand: 'CENTURY'},
   {unit: 35, brand: 'BADGER'},
   {unit: 25, brand: 'CENTURY'},
   {unit: 15, brand: 'CENTURY'},
   {unit: 25, brand: 'XEGAR'}
];

We are required to write a function that groups all the brand properties of objects whose unit property is the same.

Like for the above array, the new array should be −

const output = [
   {unit: 35, brand: 'CENTURY, BADGER'},
   {unit: 25, brand: 'CENTURY, XEGAR'},
   {unit: 15, brand: 'CENTURY'}
];

We will loop over the array, search for the object with unit value using a helper function. If it exists, we concatenate the brand value otherwise we create a new object.

Example

Following is the code −

const arr = [
   {unit: 35, brand: 'CENTURY'},
   {unit: 35, brand: 'BADGER'},
   {unit: 25, brand: 'CENTURY'},
   {unit: 15, brand: 'CENTURY'},
   {unit: 25, brand: 'XEGAR'}
];
const indexOf = function(unit){
   return this.findIndex(el => el.unit === unit)
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const ind = res.indexOf(arr[i].unit);
      if(ind !== -1){
         res[ind].brand += `, ${arr[i].brand}`;
      }else{
         res.push(arr[i]);
      }
   };
   return res;
};
console.log(groupArray(arr));

Output

This will produce the following output in console −

[
   { unit: 35, brand: 'CENTURY, BADGER' },
   { unit: 25, brand: 'CENTURY, XEGAR' },
   { unit: 15, brand: 'CENTURY' }
]

Updated on: 18-Sep-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements