Array grouping on the basis of children object’s property in JavaScript


We have an array of objects that contains data about some cars. The array is given as follows −

const cars = [{
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Hyundai',
   type: 'Sedan'
}, {
   company: 'Suzuki',
   type: 'Sedan'
}, {
   company: 'Audi',
   type: 'Coupe'
}, {
   company: 'Tata',
   type: 'SUV'
}, {
   company: 'Morris Garage',
   type: 'Hatchback'
}, {
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Tata',
   type: 'Sedan'
}, {
   company: 'Honda',
   type: 'Hatchback'
}];

We are required to write a program that groups the object together so that all the objects having the same value for type property appear together.

We will simply sort the array according to the type property so that the objects get aligned in alphabetical order of the types property.

The full code for doing this will be −

const cars = [{
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Hyundai',
   type: 'Sedan'
}, {
   company: 'Suzuki',
   type: 'Sedan'
}, {
   company: 'Audi',
   type: 'Coupe'
}, {
   company: 'Tata',
   type: 'SUV'
}, {
   company: 'Morris Garage',
   type: 'Hatchback'
}, {
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Tata',
   type: 'Sedan'
}, {
   company: 'Honda',
   type: 'Hatchback'
}];
const sorter = (a, b) => {
   return a.type.toLowerCase() > b.type.toLowerCase() ? 1 : -1;
}
cars.sort(sorter);
console.log(cars);

The output in the console will be −

[
   { company: 'Audi', type: 'Coupe' },
   { company: 'Honda', type: 'Hatchback' },
   { company: 'Morris Garage', type: 'Hatchback' },
   { company: 'Tata', type: 'Sedan' },
   { company: 'Suzuki', type: 'Sedan' },
   { company: 'Hyundai', type: 'Sedan' },
   { company: 'Honda', type: 'SUV' },
   { company: 'Tata', type: 'SUV' },
   { company: 'Honda', type: 'SUV' }
]

Updated on: 09-Oct-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements