
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array Grouping by 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' } ]
Advertisements