Add up the monthly totals of an array of objects using JavaScript

I have a set of objects arranged in the following manner:

var json = [ { day: '01-01-2018', hour: '00:00', value: '121' }, { day: '01-02-2018', hour: '05:24', value: '131' }, { day: '26-01-2018', hour: '00:07', value: '101' }, { day: '16-02-2018', hour: '08:02', value: '56' }, { day: '20-02-2018', hour: '12:02', value: '123' }, { day: '24-03-2018', hour: '10:11', value: '45' }];

I am looking to convert the date format from DD-MM-YYYY to YYYY-MM-DD and then aggregate values by month to visualize them on a chart.

This is what I have tried so far:

var mapDateVolume = [];

 for (var i = 0; i < json.length; i++)
        {
            var allDate = json[i].day;
            var oneVolume = json[i].value;
            var splitedDate = allDate.split("-");
            var newOrderY = splitedDate[2] + "-" 
            var newOrderM = splitedDate[1] + "-";
            var newOrderD = splitedDate[0];
            var newOrderAllDate = newOrderY + newOrderM + newOrderD;  

            var newOrder = {};
            newOrder[newOrderAllDate] = oneVolume;
            mapDateVolume.push(newOrder);

        }

var result = [];

        for (var i = 0; i < mapDateVolume.length; i++){

            var key = Object.keys(mapDateVolume)[i].split("-")[0] + "/";
            key += Object.keys(mapDateVolume)[i].split("-")[1];
            var value = Object.values(mapDateVolume)[i];
            var oldValue = Object.keys(result)[i] != null ? Object.keys(result)[i] : 0;

            var newResult = {};
            newResult[key] = value;
            result.push(newResult);
        }

        for (var i = 0; i < result.length; i++) {

            xAxis.push(Object.keys(result)[i]);
            yAxis.push(Object.values(result)[i]);

        }

I am using Chart.js and it displays fine with days like this:

 for ( var i = 0; i < jsonAll.length; i++ )
 {

   xAxis.push(json[i].day+'-'+json[i].hour);
   yAxis.push(json[i].value);

 }

I believe there might be an issue with my aggregation process as I only see an empty chart. Unfortunately, JavaScript is not my strong suit yet.

Answer №1

Let's start by formatting the entire collection (data array).

The steps we need to take are:

  1. Change the date format from DD-MM-YYYY to YYYY-MM-DD.
  2. Convert the value property from a string type to a number.

We can easily achieve this using the Array#Map method:

const collection = data.map(x => ({ ...x, day: x.day.split("-").reverse().join("-"), value: Number(x.value)}));

Next, let's use Array#Map again to replace the day property with the corresponding Month:

const mapDayToMonth = collection.map(x => ({...x, day: new Date(x.day).getMonth()}));

The getMonth() method returns the month (from 0 to 11) for the specified date based on local time. Where 0 is January, 1 is February, and so on.

Lastly, we'll utilize Array#Reduce to calculate the total value per Month:

const sumPerMonth = mapDayToMonth.reduce((acc, cur) => {
  acc[cur.day] = acc[cur.day] + cur.value || cur.value;
  return acc;
}, {})

Check out this complete example on JSFiddle:

const data = [ { day: '01-01-2018', hour: '00:00', value: '121' }, { day: '01-02-2018', hour: '05:24', value: '131' }, { day: '26-01-2018', hour: '00:07', value: '101' }, { day: '16-02-2018', hour: '08:02', 
value: '56' }, { day: '20-02-2018', hour: '12:02', value: '123' }, { day: '24-03-2018', hour: '10:11', value: '45' }];

    const collection = data.map(x => ({ ...x, day: x.day.split("-").reverse().join("-"), value: Number(x.value)}));

    console.log(collection);

    const mapDayToMonth = collection.map(x => ({...x, day: new Date(x.day).getMonth()}));

    console.log(mapDayToMonth);

    const sumPerMonth = mapDayToMonth.reduce((acc, cur) => {
      acc[cur.day] = acc[cur.day] + cur.value || cur.value;
      return acc;
    }, {})

    console.log(sumPerMonth)

Here are some useful links for further reference:

Array Map

Array Reduce

Number Object

Spread Syntax

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

Implementing an array of functions on an array of elements based on their positions

Imagine the scenario: def x_squared(x): result = x * x return result def twice_x(x): result = 2 * x return result def x_cubed(x): result = x * x * x return result x_values = np.array([1, 2, 3]) functions = np.array([x_squared, t ...

I am struggling to comprehend the data organization illustrated by the typescript type declaration

type DocumentData = { [field: string]: any }; let data1: DocumentData = {4:3}; console.log(data1); //{4:3} It appears that the DocumentData type in the code above defines an object type where the key is of string type and the value can be of any type. Th ...

From mongoose to swagger: "<field>" validation error - BSONTypeError: The argument provided must be a string containing either 12 bytes or 24 hexadecimal characters

I'm currently working on developing a REST API using Express, Mongoose, and Swagger for API documentation. To automate the process of converting my existing schema to Swagger, I utilized the mongoose-to-swagger package. However, I encountered an issue ...

What is the process for refreshing a user's session from the backend following updates to their metadata?

Currently, I am utilizing Next.js on the client side, auth0 for authentication, and Django Rest Framework for the backend. By following Auth0's Manage Metadata Using the Management API guide, I successfully managed to set new metadata values (verified ...

Checking if a value exists in a Bash array using AWK

Within an awk script, I am working with a file where each line includes a number ranging from 1 to 16 in the fifth field, denoted as $5. For instance: X;X;X;X;1;X;X X;X;X;X;8;X;X X;X;X;X;25;X;X X;X;X;X;5;X;X The objective is to examine the numbers in fiel ...

Embed a variable within the append function of jQuery

I am attempting to add multiple divs inside another div using a for loop in jQuery. The goal is to assign a unique ID to each div based on the iteration value of i. I have attempted to concatenate the value of i within the string, but it has not been succe ...

What is the best way to incorporate npm packages and ES6 features into Django?

As I work on the frontend development of my Django application, I am keen on incorporating the official material design components. Yet, I am faced with a challenge in seamlessly integrating these components. I am looking for a way to import the npm packa ...

Selenium - Unable to click on element at current location

I encountered an error while using Selenium for my test script. The error seems to occur randomly and is not consistently reproducible. When I run the test 10 times, it occurs about twice. The element I'm attempting to click on is clearly visible in t ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

Utilize an array-variable in VBA to maximize the effectiveness of your SQL WHERE clause

Is there a way to insert an array, stored in a variable, into the WHERE clause of a SQL statement in VBA? recordset1.Open "SELECT * FROM [Table] WHERE [NettingSet] = '" & varRecord & "'" The original string is: recordset1.Open "SELECT ...

Discover the optimal path and most competitive cost within an array

How can you efficiently determine the cheapest route for customers? For instance, how do you compare prices between Guarulhos to Rio or Sao Paulo to Rio. In the code snippet provided, I am looking to specifically display the route with the lowest combine ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Tips for aligning the timer on a client's webpage with the server

What is the most effective method to synchronize the time displayed on a webpage with the server? My webpage requires that a countdown begins simultaneously for all users and ends at precisely the same time to avoid any user gaining a time advantage. Whi ...

Can dates be reformatted or converted for a 13-month calendar (Georgian calendar)?

There is a movement among calendar reformers to standardize the length of each month in a year. One proposed method involves creating a calendar with 13 months, each consisting of 4 weeks (28 days), resulting in a total of 364 days. The earliest known inst ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

Unusual Behavior of a 2D Array

int[][] array = new int[3][3]; for(int i=0; i<array.length; i++){ for(int j=0; j<array[i].length; j++){ array[j][i] = j; System.out.print(array[i][j]); } System.out.println(); } Hello, I am a ...

Encountering issue with Mailchimp post request in React app

As I am developing my web application using React without a backend, I encountered an issue while trying to integrate MailChimp. The error message that I received is as follows: ContactUs.jsx:40 POST http://localhost:3000/3.0/lists/{api-key} 404 (Not F ...

Retrieving JSON Data Using JavaScript from a Web Service

After clicking the button in my HTML file to execute the JavaScript, I encounter this error: myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Here is the JS code: fun ...

Using three.js to cast rays on a mesh with skinning simulation

Attempting to perform a raycast on a skinned mesh post-skeleton alterations, with no animations involved to prioritize performance. The challenge in this endeavor includes: Load skinned mesh and add it to the scene Make changes to the positions of speci ...

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...