- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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' ] } ]
Advertisements