
- 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
Group objects by property in JavaScript
Suppose, we have an array of objects that contains data about some fruits and vegetables like this −
const arr = [ {food: 'apple', type: 'fruit'}, {food: 'potato', type: 'vegetable'}, {food: 'banana', type: 'fruit'}, ];
We are required to write a JavaScript function that takes in one such array.
Our function should then group the array objects based on the "type" property of the objects.
It means that all the "fruit" type objects are grouped together and the "vegetable' type grouped together separately.
Example
The code for this will be −
const arr = [ {food: 'apple', type: 'fruit'}, {food: 'potato', type: 'vegetable'}, {food: 'banana', type: 'fruit'}, ]; const transformArray = (arr = []) => { const res = []; const map = {}; let i, j, curr; for (i = 0, j = arr.length; i < j; i++) { curr = arr[i]; if (!(curr.type in map)) { map[curr.type] = {type: curr.type, foods: []}; res.push(map[curr.type]); }; map[curr.type].foods.push(curr.food); }; return res; }; console.log(transformArray(arr));
Output
And the output in the console will be −
[ { type: 'fruit', foods: [ 'apple', 'banana' ] }, { type: 'vegetable', foods: [ 'potato' ] } ]
- Related Questions & Answers
- How to group array of objects by Id in JavaScript?
- How to group an array of objects by key in JavaScript
- Sorting an array of objects by property values - JavaScript
- Sort array of objects by string property value - JavaScript
- Filter array of objects by a specific property in JavaScript?
- Sort array of objects by string property value in JavaScript
- Sorting an array objects by property having null value in JavaScript
- Group objects inside the nested array JavaScript
- Group by JavaScript Array Object
- Group by element in array JavaScript
- Searching objects by value in JavaScript
- Group values on same property - JavaScript
- Group array by equal values JavaScript
- Sorting objects by numeric values - JavaScript
- Join two objects by key in JavaScript
Advertisements