What is the process for converting monthly data into an array?

I am working with an array of daily data that looks like this:

var data = [{x: '2017-01-01', y: 100}, {x: '2017-01-02', y: 99}, /* entire year. */];

Each element in the array has an x field for date and a y field for a number. This array contains data for an entire year.

I am looking to generate an output array where each element is the sum of y values for every month, like so:

var output = [10000, 9999, ...]

I am unsure if JavaScript has a function similar to 'GROUP BY' in SQL. If it does, perhaps I can use a reduce method to accumulate data for each month. Can you please provide assistance?

Answer №1

An efficient way to handle this would be to create a result set for each month, including those with zero values, and then iterate through the data. By using the month as an index adjusted to zero-based, you can easily add up the values for each item.

var data = [{ x: '2017-01-01', y: 100 }, { x: '2017-01-02', y: 99 }, { x: '2017-01-02', y: 99 }, { x: '2017-02-02', y: 10 }, { x: '2017-04-02', y: 42 }],
    result = Array.apply(null, { length: 12 }).map(function () { return 0; });

data.forEach(function (o) {
    result[o.x.slice(5, 7) - 1] += o.y;
});

console.log(result);
.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

Designing a versatile DIV that sorts through components with the power of HTML, CSS, and JavaScript

I have been exploring a tutorial on W3 about filtering elements using JavaScript. Here is the link to the tutorial: W3 filter elements After following the tutorial, I noticed that the implementation leaves white space on the right side of the elements whe ...

The fetch API is being restricted, however, AJAX and XHR are still operational

I made an API call to a URL shortener and encountered different responses using Fetch, JQuery, and XHR. Why is Fetch returning a 400 error while the other methods work smoothly? Even after trying mode: 'no-cors' and "crossDomain": true in the re ...

Transform a javascript object with class attributes into a simple object while keeping the methods

I am seeking a way to convert an instance of a class into a plain object, while retaining both methods and inherited properties. Here is an example scenario: class Human { height: number; weight: number; constructor() { this.height = 1 ...

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

Having trouble sending a prop to an API function from UseEffect in React with Next.js

Currently, I am utilizing the App Router within next.js. I am encountering difficulties when attempting to pass serial_num as an argument to my API function fetchImages from within the useEffect in my page.tsx file. The API function can be found in /app/ ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

Get the values of var1 and var2 from the URL in PHP, for example: `example.php?var1

Currently, a portion of my website operates by using GET requests to navigate to profiles or pages. However, I am concerned about the scenario where a user visits someone's profile page (requiring one GET) and then clicks on a sub-tab within that prof ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

Exploring ES6 classes in Java Script: accessing prototype properties

After searching extensively for an answer and coming up empty-handed, I decided to pose my question here. When creating an object constructor in JavaScript as shown below: function Car(speed){ this.speed = speed; this.position = 0; } Car.prototype.m ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

An unconventional way to display an image using the :before pseudo-element and a data attribute in CSS

My goal is to use the :before pseudo-element to set an image background, as I plan to overlay content on top of it. In the past, I have dynamically set a data attribute with :before for other purposes. Question: Is there a way to change the number using ...

Getting rid of the backslash from a JSON object in an Axios POST request

Question regarding adding a reverse slash to a JSON file when making an Axios post request. Despite using the replace function, the backslash remains in the final output. axios .post( "https://test-manager/backend", { ...

Acquire information from a Card using Oracle Apex

I have a Card Regions that showcases some of my tables. I'd like each card to redirect to a specific page based on a number (the "page_table" number corresponds to the page it will redirect to). Below is the Query for the Cards Region: SELECT table_n ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

Enhancing Image Source URLs with Dynamic Content Using HTML and JavaScript

<img src="https://website.example/convention?plastic_id=**{add-id-here}**&muppet_id=**{add-id-here}**"> I am currently facing a challenge in injecting dynamic content from an external database into the {add-id-here} placeholders. While ...