Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it.

Here is an array of objects:

[
   {
    "date": "2015-01-01T12:00:00.000Z",
    "photoUrl": "",
    "inProgress": false,
    "isCompleted": true,
    "size": 1024
   },
   ...
]

I'm seeking a straightforward solution to group these objects by year, then by month, and finally by day in the specified format.

The desired result should be an iterable structure as follows:

[
   {
    "2015": [
       {
        "JAN": [
           {
            "01": { ... },
            "02": { ... }
           }
         ],
        "FEB": [
           {
            "01": { ... },
            "02": { ... }
          }
        ]
      }
     ],
    "2016": [
       {
        "APR": [
           {
            "02": { ... }
           }
         ]
       }
     ]
   }
]

This transformation will enable easy iteration using ng-repeat in Angular.

If anyone has suggestions, this code could prove useful to others as there are no existing examples of converting a flat array of dates into a structured object of year, month, and day available online.

Thank you very much!

Answer №1

To ensure that the year is set, first check if it is defined and if not, assign an array with an empty object to it. Then move on to the month and proceed to assign the item accordingly.

var data = [{ date: "2015-01-01T12:00:00.000Z", photoUrl: "", inProgress: false, isCompleted: true, size: 1024 }, { date: "2015-01-02T12:00:00.000Z", photoUrl: "", inProgress: false, isCompleted: false, size: 1024 }, { date: "2015-02-01T12:00:00.000Z", photoUrl: "", inProgress: true, isCompleted: false, size: 1024 }, { date: "2015-02-02T12:00:00.000Z", photoUrl: "", inProgress: false, isCompleted: true, size: 1024 }, { date: "2016-04-01T12:00:00.000Z", photoUrl: "", inProgress: true, isCompleted: false, size: 1024 }, { date: "2016-04-02T12:00:00.000Z", photoUrl: "", inProgress: false, isCompleted: true, size: 1024 }],
    grouped = Object.create(null);

data.forEach(function (a) {
    var year = a.date.slice(0, 4),
        month = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'][a.date.slice(5, 7) - 1],
        day = a.date.slice(8, 10);

    grouped[year] = grouped[year] || [{}];
    grouped[year][0][month] = grouped[year][0][month] || [{}];
    grouped[year][0][month][0][day] = a;
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Regrettably, it appears that further reduction is not possible due to the varying key/value requirements at each level.

var data = [{"date":"2015-01-01T12:00:00.000Z","photoUrl":"","inProgress":false,"isCompleted":true,"size":1024},{"date":"2015-01-02T12:00:00.000Z","photoUrl":"","inProgress":false,"isCompleted":false,"size":1024},{"date":"2015-02-01T12:00:00.000Z","photoUrl":"","inProgress":true,"isCompleted":false,"size":1024},{"date":"2015-02-02T12:00:00.000Z","photoUrl":"","inProgress":false,"isCompleted":true,"size":1024},{"date":"2016-04-01T12:00:00.000Z","photoUrl":"","inProgress":true,"isCompleted":false,"size":1024},{"date":"2016-04-02T12:00:00.000Z","photoUrl":"","inProgress":false,"isCompleted":true,"size":1024  }];
var months = [,"JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var re = /^(\d{4})-(\d{2})-(\d{2})/;
var results = data.reduce(function(results,value){
  var date = value.date.match(re);
  var temp = results;
  var key = date[1];
  if(!temp.hasOwnProperty(key)) temp[key] = {};
  temp = temp[key];
  key = months[date[2]|0];
  if(!temp.hasOwnProperty(key)) temp[key] = {};
  temp = temp[key];
  key = date[3];
  if(!temp.hasOwnProperty(key)) temp[key] = [];
  temp = temp[key];
  
  temp.push(value);
  return results;
},{});
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

Tips for running a JavaScript function that is returned in an AJAX response

I am facing an issue with executing a function after a successful Ajax request in my jQuery code. Here is the snippet of my code: $.ajax({ type: "POST", url: "https://www.example.com/create_chat.php", data: dataString, beforeSe ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...

What are some of the potential drawbacks of utilizing the same template ref values repeatedly in Vue 3?

Is it problematic to have duplicate template ref values, such as ref="foo", for the same type but different instances of a component across views in a Vue 3 application? Let's consider the following example pseudocode: // ROUTE A <te ...

Utilize NgRepeat to access an unidentified array in AngularJS

In a complex multi-level array, there are objects nested at the deepest level. [ [ [ "FUND", { "totassets":10.9, "totdate":"2015-03-23", "expratiogross":1.35, "exprationet" ...

What is the best way to choose an HTML element in React?

Is there a way in React to change the theme value based on localStorage and set it to either light or dark mode? https://i.sstatic.net/Iecsj.jpg I am familiar with using Ref hooks in components, but how can I access a DOM element in the index.html file? ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

Combining objects while utilizing SetState within a loop: a guide

Inside my component, the state is structured as follows: class MainClass constructor(props) { super(props); this.state = { form: { startDate:"1/11/2020", endDate:"5/11/2020", .... }, ...

Injecting $scope and constants into an abstract state controller using ui router is not supported

I am currently utilizing angular 1.3.11 with the latest ui router version. Whenever I inject $scope or constants into my DateplannerController like so: 'use strict'; angular.module('test').controller('DateplannerController', ...

Problem with parsing JSON in a mixed array

When making a YouTube API call, the response includes a var result = JSON.stringify(response, '', 2); that has the following structure: { "kind": "youtube#searchListResponse", "pageInfo": { "totalResults": 1000000, ...

Change every occurrence of span class red to be a strike tag

I'm attempting to replace all span tags with the red class and their content with a strike tag. However, I've encountered an issue where it doesn't seem to be replacing the specific span tags as expected. Below is the code snippet: let s ...

Embed script tags into static HTML files served by a Node.js server

Looking to set up a Node server where users can request multiple pages from a static folder, and have the server inject a custom tag before serving them. Has anyone had success doing this? I've tried with http-proxy without success - not sure if a pro ...

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

Troubleshooting: ng-disabled not function properly in Angular.js

My goal is to only allow the button to be enabled if there is text in the textfield, but for some reason I am unable to make ng-disabled work: <form novalidate> <button type="submit" ng-click="add('+')" ng-disabled="bittext.$invalid ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

Before computing the width, Next.js Swiper slide occupies the entire width

Check out the code snippet below: 'use client'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; import 'swiper/css/pagination'; export default function Component() { const cards = [{ id: 0 ...