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

Tips for implementing Material-UI components in a .ts file

I am currently working on some .ts files for mocks, and I have a question about inserting MUI elements such as the Facebook icon. export const links: Link[] = [ { url: "https://uk-ua.facebook.com/", **icon: <Facebook fontSize ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Select all elements using jQuery that have an id attribute and belong to a specific class

I am attempting to select all items with an ID attribute that starts with a specified string while also having a particular class. For instance, consider the following: <div id="test-id-1" class="test"></div> <div id="test-id-2" class="test ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Utilizing Vue.js 2.x to send a REST API request with a collection of objects

I currently have an array of objects stored in state, and my goal is to send this entire structure to a back end API for processing and receive a new set of values in return. Below is a simplified representation of this structure as viewed in the develope ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

Clicking on a DIV using jQuery, with anchor elements

I have a method for creating clickable divs that works well for me: <div class="clickable" url="http://google.com"> blah blah </div> Afterwards, I use the following jQuery code: $("div.clickable").click( function() { window.location ...

Is WebStorm with Node Supervisor being utilized to eliminate the need for restarting after every code modification?

Currently, I am utilizing WebStorm as my node IDE and have found it to be quite impressive. However, one issue I am facing is figuring out how to incorporate node supervisor into my workflow within WebStorm. Has anyone successfully managed to set this up ...

How can React and react-router be used to direct users to a specific group of URLs

One scenario I have is when my users upload a group of photos, they need to add specific meta information for each one. After uploading the files, I want to direct them to the first photo's meta editor page. Then, when they click on the "next" button, ...

A guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

Manually incorporating multiple React components into a single container

I am currently in the process of upgrading an old JavaScript application that relies heavily on jQuery by introducing some React components. The existing code utilizes JS/jQuery to dynamically add elements to the DOM, and I am looking for a way to replace ...

Preventing unauthorized access to files in ExpressJS public directories

Is there a way to conceal files served by the Node server? Despite my attempts to redirect certain files and directories, Express 4.X does not seem to cooperate. I have also experimented with sending 4XX HTTP responses when specific files are requested, bu ...

The automatic type inference in Typescript is faulty

I am currently working with TypeScript version ^4.1.3 and have developed a REST API that deals with albums and art collections. Before sending the response to the web client, I make sure to remove the userId property from the collections. Below are my Alb ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

Activate the display by utilizing the getElementsByClassName method

In my design, I'd like to have the "Don't have an account?" line trigger the display of the .registrybox class when clicked. However, the script I've written doesn't seem to be working as intended. The script is meant to hide the .login ...