Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can assist me with this task. Any explanation or code reference would greatly help. Here is a snippet of my JSON result:

[
  {
    "createdAt": "2019-12-30T04:36:05.001Z"
  },
  {
    "createdAt": "2019-12-06T08:58:23.030Z"
  },
  {
    "createdAt": "2020-01-08T19:00:21.873Z"
  },
  {
    "createdAt": "2020-01-10T14:55:50.781Z"
  },
  {
    "createdAt": "2019-12-21T13:05:09.983Z"
  },
  {
    "createdAt": "2020-01-15T12:10:20.316Z"
  },
  {
    "createdAt": "2020-01-14T06:47:36.078Z"
  },
  {
    "createdAt": "2020-02-15-T06:47:36.078Z"
  }
]

As I am using Angular, the data from the service is being fetched. Now, I need to display the total number of parcels created for each month.

Answer №1

If you want to extract a part of the date string in ISO 8601 format as a key and then count occurrences using an object, you can achieve this by following these steps:

var data = [{ createdAt: "2019-12-30T04:36:05.001Z" }, { createdAt: "2019-12-06T08:58:23.030Z" }, { createdAt: "2020-01-08T19:00:21.873Z" }, { createdAt: "2020-01-10T14:55:50.781Z" }, { createdAt: "2019-12-21T13:05:09.983Z" }, { createdAt: "2020-01-15T12:10:20.316Z" }, { createdAt: "2020-01-14T06:47:36.078Z" }, { createdAt: "2020-02-15-T06:47:36.078Z" }],
    result = data.reduce((r, { createdAt }) => {
        var key = createdAt.slice(0, 7);
        r[key] = (r[key] || 0) + 1;
        return r;
    }, {});

console.log(result);

Answer №2

If you want to condense your data, consider utilizing the Array.prototype.reduce() method.

const src = [{"createdAt":"2019-12-30T04:36:05.001Z"},{"createdAt":"2019-12-06T08:58:23.030Z"},{"createdAt":"2020-01-08T19:00:21.873Z"},{"createdAt":"2020-01-10T14:55:50.781Z"},{"createdAt":"2019-12-21T13:05:09.983Z"},{"createdAt":"2020-01-15T12:10:20.316Z"},{"createdAt":"2020-01-14T06:47:36.078Z"},{"createdAt":"2020-02-15T06:47:36.078Z"}],
      summary = src.reduce((res,{createdAt}) => {
        const year = new Date(createdAt).getFullYear(),
              month = new Date(createdAt).getMonth()+1           
        res[`${year}-${month}`] = (res[`${year}-${month}`] || 0) + 1
        return res
      }, {})
      
console.log(summary)      

Please note, the code snippet above will function properly as long as your createdAt strings are formatted in a way that can be parsed by the new Date() constructor, not just ISO-formatted dates.

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

Reducing the size of associative PHP arrays by compacting them

Given the array below in PHP: array('red','blue','green','purple'); I am looking for a simple and quick way to transform that array into this format: array('red'=>'blue','green'=&g ...

Having trouble retrieving data sent via ajax in PHP

Currently, I am using Ajax to send a variable in my PHP file. Here's the code snippet: getVoteCount: function(){ App.contracts.Election.deployed().then(function(instance) { for(i=0; i<4; i++){ instance.candidates(i).then(functi ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

Angular offers a range of search filters for optimizing search results

The system currently has 3 search fields: 1. Name.... 2. Subject.... 3.Price.... Each of these filters works independently - when searching by name, only results matching that name are displayed; similarly for subject and price. However, the challeng ...

What is the best way to prevent event bubbling in this particular code snippet?

$('#div1').on('click', '#otherDiv1', function(event){ //Show popup $('#popupDiv').bPopup({ modalClose: false, follow: [false, false], closeClass: 'close ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Create an AngularJS Directive that will display an array of n elements in the form of m rows of tables

Challenge: I have an array of 'n' items that I need to display in separate tables, with each table containing m rows. For instance, if n=30 and m=6, then I should have 5 tables each with 6 items displayed horizontally. Proposed Solution: I attem ...

Error: The function scrollIntoView is invalid and cannot be found

I'm currently new to working with react-testing-library / jest and trying to create a test that checks if the route navigation (using react-router-dom) is functioning correctly. I've been following the guidance from the README as well as this hel ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

Is there a way to send arguments to a pre-existing Vue JS application?

A Vue application we've developed connects to a Web Service to retrieve data. However, the URL of the web service varies depending on the installation location of the app. Initially, we considered using .env files for configuration, but realized that ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...

Is it necessary to include explicit overlapping imports in Angular if they are already imported in the parent component?

Do you think the title needs clarification? Feel free to offer suggestions. I've noticed that my design components are ending up with a lot of imports. Some of these imports are duplicated in the component that is importing them. I'm managing to ...

Struggling to locate a straightforward sidebar solution without relying on Bootstrap. Finding an easy-to-use answer seems

I have a lightweight and easy-to-understand code for a website project with two panels. The first panel on the left is a large navigation (270px width, top to bottom, similar to a wiki) with approximately 30 unordered list items. Next to it is the second ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

“Unlocking the secret to extracting color from an image in React Native”

While it may sound like a silly question, I am new to the world of React technology. I am looking to extract colors from an image - for example, when a user selects an image to upload, I want to identify all the colors used in that image. If this is possib ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Is it possible to use the Husky "commit-msg" hook to git add new files?

I am currently setting up an automatic versioning system where if I use git commit with the message format PATCH: {message}, the app's patch version will automatically be updated (and the same for the prefixes MINOR and MAJOR as well). My approach inv ...

Stuck on loading screen with Angular 2 Testing App

Currently working on creating a test app for Angular 2, but encountering an issue where my application is continuously stuck on the "Loading..." screen. Below are the various files involved: app.component.ts: import {Component} from '@angular/core& ...