
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 groupby 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 } ] }
- Related Questions & Answers
- Most efficient method to groupby on an array of objects - JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- Converting array of objects to an object of objects in JavaScript
- What is the most efficient way to deep clone an object in JavaScript?
- Using methods of array on array of JavaScript objects?
- Sorting an array of objects by an array JavaScript
- What is the most efficient string concatenation method in python?
- Search from an array of objects via array of string to get array of objects in JavaScript
- Converting array of objects to an object in JavaScript
- How to sort an array of objects based on the length of a nested array in JavaScript
- GroupBy() Method in C#
- Splitting an object into an array of objects in JavaScript
- Can we share a method between JavaScript objects in an array?
- How to access properties of an array of objects in JavaScript?
Advertisements