

- 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 by element in array JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ];
We are required to write a JavaScript function that splits the objects into separate array of arrays that have the similar values for the uuid property.
Output
Therefore, the output should look like this −
const output = [ [ {"name": "toto", "uuid": 1111}, {"name": "titi", "uuid": 1111} ], [ {"name": "tata", "uuid": 2222} ] ];
The code for this will be −
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ]; const groupByElement = arr => { const hash = Object.create(null), result = []; arr.forEach(el => { if (!hash[el.uuid]) { hash[el.uuid] = []; result.push(hash[el.uuid]); }; hash[el.uuid].push(el); }); return result; }; console.log(groupByElement(arr));
Output
The output in the console −
[ [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ], [ { name: 'tata', uuid: 2222 } ] ]
- Related Questions & Answers
- Group by JavaScript Array Object
- Group matching element in array in JavaScript
- Group array by equal values JavaScript
- Group values in array by two properties JavaScript
- How to group array of objects by Id in JavaScript?
- JavaScript Splitting string by given array element
- Group a JavaScript Array
- Group objects by property in JavaScript
- How to group an array of objects by key in JavaScript
- GROUP BY the number of rows returned by GROUP BY in MySQL?
- Group MySQL rows in an array by column value?
- Remove element by id in JavaScript?
- How to group Python tuple elements by their first element?
- Listing all rows by group with MySQL GROUP BY?
- Group objects inside the nested array JavaScript
Advertisements