- 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
Grouping data to monthwise in JavaScript
Suppose we have some data about some users like this −
const obj = { "Mary": { "2016-1": 2, "2016-5": 1, "2016-3": 1 }, "Paul": { "2016-1": 1, "2016-3": 1 }, "moth": { "2016-1": 2, "2016-5": 1 } };
We are required to write a JavaScript function that takes in one such object. Our function should group this user data into objects where each unique date is represented by an object.
Example
The code for this will be −
const obj = { "Mary": { "2016-1": 2, "2016-5": 1, "2016-3": 1 }, "Paul": { "2016-1": 1, "2016-3": 1 }, "moth": { "2016-1": 2, "2016-5": 1 } }; const groupByDate = (obj = {}) => { const names = Object.keys(obj); const res = {}; for(let i = 0; i < names.length; i++){ const name = names[i]; const dates = Object.keys(obj[name]); for(let j = 0; j < dates.length; j++){ const date = dates[j]; if(!res.hasOwnProperty(date)){ res[date] = { names: [name], values: [obj[name][date]] } } else{ res[date].names.push(name); res[date].values.push(obj[name][date]); }; }; }; return res; }; console.log(groupByDate(obj));
Output
And the output in the console will be −
{ '2016-1': { names: [ 'Mary', 'Paul', 'moth' ], values: [ 2, 1, 2 ] }, '2016-5': { names: [ 'Mary', 'moth' ], values: [ 1, 1 ] }, '2016-3': { names: [ 'Mary', 'Paul' ], values: [ 1, 1 ] } }
- Related Articles
- Explain Grouping operator in JavaScript.
- Grouping array values in JavaScript
- Grouping nested array in JavaScript
- Complicated array grouping JavaScript
- Grouping words with their anagrams in JavaScript
- How to apply different function to grouping values in an R data frame?
- Grouping identical entries into subarrays - JavaScript
- Grouping objects based on key property in JavaScript
- Grouping names based on first letter in JavaScript
- Grouping and sorting 2-D array in JavaScript
- Grouping of same kind of numbers in JavaScript
- Grouping on the basis of object property JavaScript
- Efficient algorithm for grouping elements and counting duplicates in JavaScript
- Grouping array nested value while comparing 2 objects - JavaScript
- Array grouping on the basis of children object’s property in JavaScript

Advertisements