- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 Articles
- Group matching element in array in JavaScript
- Group by JavaScript Array Object
- 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
- How to group an array of objects by key in JavaScript
- Group a JavaScript Array
- Group objects by property in JavaScript
- Searching an element in Javascript Array
- JavaScript One fourth element in array
- First element and last element in a JavaScript array?
- Compress array to group consecutive elements JavaScript
- Group objects inside the nested array JavaScript
- Group MySQL rows in an array by column value?

Advertisements