arranging and combining data arrays by individual elements

I am looking to group payments by month into a new array, regardless of the account type given by 3 categories (DEA, ISA, SIPP).

The data I have is structured as follows:

var arr = [
        { 'DEA','1', 'Jan',1266 },
        { 'ISA','1', 'Jan',621 },
        { 'SIPP','1', 'Jan',552 },
        { 'DEA','2', 'Feb',889 },
        { 'ISA','2', 'Feb',921 },
        { 'SIPP','2', 'Feb',901 },
      ];

The month number (e.g. 1 or 2) in the data is unnecessary for my desired output.

I aim to consolidate and organize the payments by month in the following format within a new array:

var newarr =
[
{ 'Jan',2439 },
{ 'Feb',2711 },
];

I currently have a code snippet that groups by age category and sums up the total amount, but I haven't been able to adapt it successfully to my payment data yet.

var arr = [
            { AGENDADOR: 'AGE270', TOTAL : 6},
            { AGENDADOR: 'AGE270', TOTAL : 3},
            { AGENDADOR: 'AGE203', TOTAL : 5},
            { AGENDADOR: 'AGE028', TOTAL : 9},
        ];
      
var totals = arr.reduce(function (r, o) {
  (r[o.AGENDADOR])? r[o.AGENDADOR] += o.TOTAL : r[o.AGENDADOR] = o.TOTAL;
  return r;
}, {});

console.log(totals);

Any assistance in getting me started with organizing the payments by month would be greatly appreciated. Thank you.

Best regards,

Colin

Answer №1

To summarize the months, one method is to maintain an array of months that can be looped through to extract the necessary values for summing.

Essentially, the reduce function organizes the values by month and the Object.values function retrieves these grouped values as an array.

This technique will extract all the months presented in the objects.

let months = ['Jan', 'Feb', 'Mar'];// and so on.
let arr = [        { 'DEA':'1', 'Jan':1266 },        { 'ISA':'1', 'Jan':621 },        { 'SIPP':'1', 'Jan':552 },        { 'DEA':'2', 'Feb':889 },        { 'ISA':'2', 'Feb':921 },        { 'SIPP':'2', 'Feb':901 }      ];
      
let result = Object.values(arr.reduce((a, c) => {
  months.forEach(m => {
    if (m in c) (a[m] || (a[m] = {[m]: 0}))[m] += c[m];
  });
  return a;
}, Object.create(null)));

console.log(result);
.as-console-wrapper { min-height: 100%; }

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 modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Nodejs for user matching flow

My current project involves creating a system where users can match with each other based on specific information. Here is the flow I am envisioning: User 1 fills in the required information and clicks "find". At the same time, User 2 also provides their ...

What is the optimal frequency for saving data when dealing with a particularly extensive form?

I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

Google Maps Info Window with Asynchronous Loading

Need help with loading a Google map asynchronously on your website? Check out the code snippet below: function initialize(lat,lng) { var mapProp = { center: new google.maps.LatLng(lat,lng), zoom:15, mapTypeId: google.maps.MapTypeId.R ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

While attempting to deploy on Vercel, I encountered an error while constructing my Next.js project

While working on my Next login signup project, I encountered the following error: WagmiProviderNotFoundError: `useConfig` must be used within `WagmiProvider`. The documentation for this issue can be found <a href="https://wagmi.sh/react/api/WagmiProvide ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Aggregate in MongoDB to organize data in arrays containing specific information

The structure of my database is as follows: {email:"user", contacts: [ {emailContact:"test", firstName:"test", lastName:"test", messages: [ {email:"user", content:"hi", date:"ISODate(...)"} {email:"test", content:"how are you?", date:"ISODa ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Data not being returned by AJAX request

I'm currently working on implementing a script in the background of my PHP pages to periodically check for new messages in the database and notify users accordingly. To achieve this, I decided to utilize AJAX to make a call to a file containing the n ...

Incorporating asynchronous file uploads to a server using a for loop

I am in the process of transforming my original code into "async" code. The initial code queries the database and retrieves the results, which includes images. I want to optimize writing the images asynchronously to my nodejs server as the current synchro ...

Creating an HTML Form that Sends an Email

I'm completely stumped as to where the issue lies! The mail() function is working perfectly fine (I tested it with a simple PHP file), but for some reason, my form isn't sending any emails! HTML <section id="contact"> <div id="go ...

Listening to multiple events in AngularJS using `$scope.$on`

I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit and take action only when both have occurred. For example, if the events are triggered in the following sequence: $scope.$emit('first&apos ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

How can I add a subdocument to a MongoDB array based on a specific condition being met?

When pushing sub documents into an array, the structure of the subdocs typically looks like this: { id:"someId", date:Date } The goal is to only add a new subdoc if there isn't already another subdoc with a matching id. The $addToSet modifier in ...

Use jQuery eq() to populate a group of text fields with data stored in localStorage

In my project, I have a series of text areas that are configured to save their content in localStorage for persistence. As I attempt to retrieve and reassign these values when the browser reloads, I encounter an issue with the following code snippet. When ...

What is the best way to calculate the average grade for each student in an array that contains objects with exam submission data?

Imagine having a collection of objects that hold details about exams submitted over a period. Here is the structure: [ { name: 'Freddy', grade: 10, date: '20/07/2022' }, { name: 'Jose', grade: 8, date:'20/07/2022& ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

Can PHP Rewrite Array Elements?

What could be causing PHP to overwrite Array elements of objects with the last iteration of the object? This behavior raises concerns regarding maintaining a record of an object's changes using an array. It seems like this could lead to potential erro ...

What is causing JavaScript to be unable to access the width property of textureImage?

I am currently facing an issue while trying to render image texture dynamically. The console is showing an error message: Uncaught TypeError: Cannot read property 'width' of undefined. Some have suggested setting needsUpdate to false, but doing s ...