Using AngularJS to categorize dates from JSON data into monthly groups and present them in visual charts

Trying to display JSON data in a chart using Chart.js and AngularJS based on months, but facing an issue with the date format being '2017-06-12T12:00:00.000Z'. Specifically, I am unsure how to group the data by month names (June, July, August, etc.) with this date format.

JSON Data

[
  {"id":1,"date":"2017-06-12T12:00:00.000Z","total":123},
  {"id":2,"date":"2017-06-04T12:00:00.000Z","total":100},
  {"id":3,"date":"2017-08-29T12:00:00.000Z","total":94}
]

Also, looking for guidance on integrating Chart.js in AngularJS to plot the dates sorted by month names on the x-axis and the totals on the y-axis.

Answer №1

After finding inspiration from a related inquiry response, I adjusted the code to organize the array based on the month and year of a specified field, such as date.

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
 

var groupByMonth = function(json_data, key_to_group) {
  // Loop through the array
  return json_data.reduce(function(array, item) {
    // Convert date string to retrieve month and year
    var item_date = new Date(item[key_to_group]);
    // Get the month name
    var item_month = monthNames[item_date.getMonth()];
    
    // Add item to new array
    (array[item_month] = array[item_month] || []).push(item);
    return array;
  }, {});
};


var arr = [
  {"id":1,"date":"2017-06-12T12:00:00.000Z","total":123},
  {"id":2,"date":"2017-06-04T12:00:00.000Z","total":100},
  {"id":3,"date":"2017-08-29T12:00:00.000Z","total":94}
];

// Call the groupByMonth method with the array you want to group, and the name of the field that contains the date
var groupedByMonth = groupByMonth(arr, 'date');
console.log(groupedByMonth);

I modified the datetime format by removing the final .. Additionally, keep in mind that grouping by month names is only effective when all data pertains to the same year.

Now, tackling the second part of your issue. You just require an array displaying the total sums by month.

// Result post grouping by month
var groupedByMonth =
{
  "June": [
    {
      "id": 1,
      "date": "2017-06-12T12:00:00.000Z",
      "total": 123
    },
    {
      "id": 2,
      "date": "2017-06-04T12:00:00.000Z",
      "total": 100
    }
  ],
  "August": [
    {
      "id": 3,
      "date": "2017-08-29T12:00:00.000Z",
      "total": 94
    }
  ]
};


// Iterate over result
var arr_totals = [];
Object.keys(groupedByMonth).forEach(function (key) {
  var month_total = 0;
  Object.keys(groupedByMonth[key]).forEach(function (subkey) {
    // Calculate total for each item within the month
    month_total += groupedByMonth[key][subkey].total;
});
  // Append monthly total to the array
  arr_totals.push(month_total);
});

console.log(arr_totals);

All that remains is to incorporate the month names as an array on the Y-axis: Object.keys(groupedByMonth), and the totals on the X-axis as per arr_totals for the desired chart type. Refer to the official Chart.js documentation for guidance.

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

Managing errors with Node.js and handling https certificates

In short: I am developing a node application that sends requests using the secure version of HTTP, which is HTTPS. When I incorrectly configure my request options, I encounter the following error: Node.js Hostname/IP doesn't match certificate' ...

Step by step guide on transferring driver control from the top window to the iframe with the id of mainFrame

Currently, I am utilizing firebug to analyze the xpath. One section of firebug indicates whether the element you are trying to locate is in the window or an iframe, among other options. I have encountered a similar issue where I see 2 available choices: 1: ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Progress bar display not available

I have recently developed a JavaScript quiz application and included a progress bar feature. While it works flawlessly offline on my laptop, I encountered an issue when uploading the files to Codepen.io - the progress bar fails to display. I would appreci ...

Retrieve an array from a json column in a postgres database and apply a mapping function to it

create table test(b json); insert into test(b) values('{"orders":[{"orderId":1}, {"orderId":2, "status":"done"}, {"orderId":3}]}'); If I have the JSON structure provided above, is it possible to extract a list or array of orderIds that do not ...

Is the sub-document _id generated by Mongoose unique?

Consider the mongoose schema below: mongoose.Schema({ world: String, color: [{ name: String }] }); This schema generates documents with sub-documents that have _id fields. { _id: 'a9ec8475bf0d285e10ca8d42' world: 'matrix', ...

What is the best way to transfer an object property to an event handler function for executing DOM manipulation tasks?

I am working on a React-rendered HTML page that displays a list of objects representing websites. I have successfully stored these objects in memory and can show them in a long list on the page without any issues. Recently, I added a button for each objec ...

Transforming JavaScript's POST Ajax into AngularJS' POST Factory

I am attempting to convert an Ajax call with WSSE authentication into an AngularJS factory. The request method is Post. The purpose of this conversion is to access the Adobe Analytics Rest API, retrieve data in JSON format, and then visualize it using d3. ...

Displaying an image in a Bootstrap 5 tooltip / Issue 304

Working on a project using Bootstrap 5. I've implemented a tooltip that displays text and an image successfully by using data-bs-html="true". Here is how my input, including the tooltip, is structured: <input class="form-control ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

Modifying an image's height and width attributes with jQuery and CSS on click action

I'm currently developing a basic gallery using HTML, CSS, and jQuery. The objective is to have a larger version of an image display in a frame with an overlay when the user clicks on it. While this works flawlessly for horizontally-oriented images, ve ...

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

When attempting to bind various data to a single div using knockout js, the issue of duplicate records appearing arises

I am encountering an issue with a div that is set up to display 10 records at a time. When the user clicks on the next link, the next set of 10 records should be loaded from the server. However, after binding the newly added records, they are being shown m ...

Unable to extract nested JSON data using JSON_TABLE in Oracle SQL

I am currently utilizing Oracle 12c(12.2) to extract json data from a table. SELECT jt.name, jt.employee_id, jt.company FROM JSON_TABLE ( BFILENAME ('DB_DIR', 'vv.json') I have encountered an issue with nested data in the j ...

Angular - Async function does not resolve a rejected promise

Currently, my component utilizes an async method for handling file uploads. Here is an example: //component uploadPhotos = async (event: Event) => { const upload = await this.uploadService.uploadPhotos(event, this.files, this.urls); } The UploadSe ...

How can the radio button's checked property be bound to a boolean attribute of a component in Angular 2?

Is there a way to connect the checked property of a radio button to a boolean variable in a Component class? I would like the radio button in the template to be pre-selected if the boolean flag is true. I attempted to use <input type="radio" [(ngModel) ...

What is the best way to iterate through states within an array using React?

Can someone help me create a button that can cycle through different states in the given array? I want the button to change State_1 to State_2, State_2 to State_3, and then back to State_1 for each object. I'm struggling to figure out how to cycle thr ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

Obtain the value from the controller of the amazing-rating component

Currently utilizing the amazing Rating AngularJS library available at https://github.com/bandraszyk/awesome-rating I am interested in understanding how to retrieve the selected value and store it in my controller. The $scope.rating is returning undefined ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...