Attempting to condense an array of objects into a consolidated and combined array of objects

My array of objects is structured like this:

dataArray = [
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Revenue: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]

I am looking to condense this array into another set of objects that appear as follows:

reducedDataArray = [
    {Revenue: 20, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]

The goal is to aggregate the revenue for entries with the same date. Limited by our version of TypeScript, I lack access to newer functionalities like ES6 features. Although I have attempted using methods like reduce(), I am struggling to navigate its intricacies in this context.

If you have any suggestions or insights on how to accomplish this task, your input would be greatly valued!

Answer №1

To create an object with date keys and then convert it back to an array, you can utilize the reduce method.

let dataArray = [
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Revenue: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]
// It is important to explicitly specify the type parameter since it will not be inferred from the initial value 
let valuesObj = dataArray.reduce<{ [date: string]: typeof dataArray[number] }>((p, v) => {
    const existing = p[v.Date];
    if (existing) {
        existing.Revenue += v.Revenue
    } else {
        p[v.Date] = Object.assign({}, v); //Creating a copy prevents changing the original during summing 
    }
    return p;
}, {});


// If available, you can use Object.values(valuesObj) 
let values = Object.keys(valuesObj).map(k => valuesaObj[k]);

Check out the playground here

Answer №2

Experimented with some loops and successfully implemented it

dataset = [
    {Sales: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Sales: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Sales: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Sales: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Sales: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
];

const findUniqueEntries=array=>{
  return array.filter((value, index, self)=> { 
      return self.indexOf(value) === index;
  });
}

let dates=[];
let result=[];

for(const entry of dataset) dates.push(entry.Date);
for(const date of findUniqueEntries(dates)){

  let total=0,date=date,dateString;
  for(const record of dataset){
    if(record.Date==date) total+=record.Sales;
    dateString=record.DateString;
  }

  result.push({
    Sales:total,
    Date:date,
    DateString:dateString
  });

}

console.log(result);

Additional jsfiddle reference

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

exploring CORS settings in fetch API for secure GET requests

My endpoint is localhost:8080/enquiry and it returns the following JSON: [{"_id":"5a283e4c5a36f4556af34742", "firstName":"bob", "surname":"hoskins", "telephoneNumber":939483948, "gender":"male", "dayOfBirth":17, "monthOfBirth":5, "ye ...

Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes. Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme. Theme setup: import { creat ...

Is there a way to verify if a FormData file has no content?

Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg. <label>Color: <input type="color" name="bgColor" value="#0000 ...

Utilize JavaScript to extract information from an HTTP Response and insert both values into a <div> element

As a novice in Javascript, I am currently grappling with the task of extracting two specific cell values from an HTTP Response provided by the Google Sheets API and inserting them into separate HTML Div elements. I am struggling with modifying my code to e ...

"Changing the size of the ArrowHelper in three.js: A step-by-step guide

I am currently working on implementing ArrowHelpers to visualize and represent forces acting on an object. In my setup, the length of the vector indicates the strength of the force being applied. However, I have encountered an issue where changing the l ...

Caution: flattenKids(): Two children with identical keys, `false`, have been detected in the ReactJS environment

Currently, I am working on creating a clickable list where each item redirects me to another page upon clicking. Below is the render method: render() { const quesItems = this.state.questions.map((question, i) => { return ( <li key={this.prop ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Finding the duration of an audio file in a React/Typescript environment

I've been attempting to determine the duration of an audio file. It seems like the audio property is not included in the file by default. The only properties I see are size, name, and type. Is there a way for me to get the duration of the audio file i ...

An Alternative Approach to Implementing the Ternary Operator in JavaScript

Do you find this logical operation to be rational? const user = users && users[0] || null; Is it identical to this conditional or ternary operation: const user = users ? users[0] : null; ? Let's assume users represents an array. ...

Tips for validating multiple inputs of the same type with identical names in JavaScript

I have limited experience with Javascript and am facing an issue with a HTML form that contains multiple input types with the same names occurring more than once. My goal is to validate the form before inserting the data into the database. I have managed t ...

tips for accessing data attributes in ajax request

I am struggling to retrieve data-id from an anchor tag when clicked using AJAX, but it keeps returning undefined. Below is my code: $image_html .= '<a class="float-left " onclick="modal()" data-toggle="modal" data-targ ...

Tips for resolving text center alignment problems along with other elements when hovering

When hovering over each ul li element, a new element is added to the right side of the text. The alignment of the text is centered by default, but upon hover, the alignment changes when the new element is added. However, the issue is that the alignment s ...

Align the date input field to the center for better visual appeal

I am facing a challenge in centering the date in an input, not the entire input element inside a div. When I attempt to center it, the date gets positioned within a portion of the input due to a resizable right-hand side panel for selecting a date from a c ...

What is the most efficient way to transmit an HTML document element from a client to a server in Node JS

I am attempting to capture a snapshot of my client-side document object and send it to the Node.js server. However, when I try to convert it into a string using: JSON.stringify(document.documentElement) I encounter an issue where it becomes an empty obje ...

A step-by-step guide on how to insert an image URL into the src attribute using the

The source of my image is -> src/assets/images/doctor1.jpg I would like to use this image here -> src/components/docNotes/docNotes.js In the docNotes.js file, I attempted -> <Avatar className={classes.avtar} alt="Remy Sharp" src ...

How is it that in TypeScript, a potential numeric value in an interface can be transformed into an impossible numeric value in a class implementation?

Encountered a surprising behavior from the TypeScript compiler today. Unsure if it's a bug or intentional feature. If it is indeed intentional, I would like to understand the reasoning behind it. The issue arises when declaring an interface method wi ...

Why are other elements not appearing on the index.html page when <app-root> is not included?

Just started delving into Angular and following some tutorials. The project was set up using Angular CLI. Created a new component named navbar on top of the default component and wanted to check if the navbar loads in the index.html at startup. The navbar ...

What is the best way to dynamically convert a lodash object (specifically a filter object) into jQuery's listview component?

After referencing the answer to this topic as my first step, which can be found here, my next goal is to utilize a filter function to retrieve all matching entries from a JSON file based on a search term. The objective is to loop through each match and con ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...