
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
Most Efficient Method to Group By on an Array of Objects in JavaScript
The most efficient method to group by a key on an array of objects in js is to use the reduce function.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Example
const people = [ { name: 'Lee', age: 21 }, { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ]; function groupBy(objectArray, property) { return objectArray.reduce((acc, obj) => { const key = obj[property]; if (!acc[key]) { acc[key] = []; } // Add object to list for given key's value acc[key].push(obj); return acc; }, {}); } const groupedPeople = groupBy(people, 'age'); console.log(groupedPeople);
Output
This will give the output −
{ 20: [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ], 21: [ { name: 'Lee', age: 21 } ] }
Advertisements