What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = 

[
  {
    "amount": 270,
    "xlabel": "25-31/10",
    "datestatus": "past",
    "color": "#E74C3C",
    "y": 270,
    "date": "2020-10-31T00:00:00Z",
    "entityId": 1,
    "entityName": "Lenovo HK",
    "bankName": "BNP Paribas Bank",
    "buyerName": "Microsoft",
    "currency": "USD"
  },
  {
    "amount": 100,
    "xlabel": "25-31/10",
    "datestatus": "past",
    "color": "#E74C3C",
    "y": 100,
    "date": "2020-10-30T00:00:00Z",
    "entityId": 1,
    "entityName": "Lenovo HK",
    "bankName": "BNP Paribas Bank",
    "buyerName": "Microsoft",
    "currency": "USD"
  },
  ...
]

function getFormationgData(data) {
    var sum = [];
    let counts = data.reduce((prev, curr) => {
      let amount = prev.get(curr.xlabel) || 0;
      prev.set(curr.xlabel, curr.amount + amount, curr.entityId, curr.entityName);
      return prev;
    }, new Map());

    // then, map your counts object back to an array
    let reducedObjArr = [...counts].map(([xlabel, amount, entityId,
      entityName]) => ({
       xlabel, amount,
        entityId,
        entityName
      }))
    //let reducedObjArr = [...counts].map(data => data)
    return reducedObjArr;
}
  
var pastData = getFormationgData(data.filter(w=>w.datestatus == 'past'));
var futureData = getFormationgData(data.filter(w=>w.datestatus == 'future'));

console.log(pastData, 'pastData', pastData.length)
console.log(futureData, 'futureData', futureData.length)
 

I'm attempting to calculate the sum of duplicate amounts in an array based on two other properties and retrieve separate arrays for past and future data.

The current dataset is as follows:

Assuming today's date is November 3, 2020

 [
{
    "amount": 270,
    "xlabel": "01-07/11", 
    "datestatus": "past",
    "color": "#E74C3C",
    "y": 270,
    "date": "2020-02-11T00:00:00Z",
    "entityId": 1,
    "entityName": "Lenovo HK",
    "bankName": "BNP Paribas Bank",
    "buyerName": "Microsoft",
    "currency": "USD"
  },

...
]

I am trying to organize this data based on `xlabel`, status, and entity. The expected result should contain separate arrays for past and future entries with all corresponding properties intact.

Although I've made some progress, I'm facing difficulties returning all properties in the object. Any assistance would be greatly appreciated!

Answer №1

I trust that I have correctly understood the task at hand.

I. Identifying Duplicate Sums

Here is a breakdown of what the algorithm accomplishes:

  1. The values from amount are sorted into two distinct arrays, one for past values and one for future values.

  2. Unique values are removed from both arrays.

  3. The total sum of the remaining values in the array is calculated.

// JavaScript data objects
var data = [
  {
    // Data object details here
  },
  // Additional data objects
];

//////////////////////////////////////////////

function calculateTotal(data, z) {

    var filteredValues = [];
    for (var i = 0; i < data.length; i++) {
      if (data[i].datestatus === z) {
        filteredValues.push(data[i].amount);
      }
    }

    function findDuplicates(array) {
      var map = new Map();
      array.forEach(a => map.set(a, (map.get(a) || 0) + 1));
      return array.filter(a => map.get(a) > 1);
    }

    var duplicates = findDuplicates(filteredValues);
    
    var result = duplicates.reduce((a, b) => a + b, 0);
    
    return result;

}

console.log(calculateTotal(data, 'past'));
console.log(calculateTotal(data, 'future'));

II. Separating Future and Past Values into Different Arrays

This function generates an array containing only future or past values from the provided data set.

function sortData(data, z) {

    var filteredData = [];
    for (var i = 0; i < data.length; i++) {
      if (data[i].datestatus === z) {
        filteredData.push(data[i]);
      }
    }

    return filteredData;

}

console.log(sortData(data, 'past'));
console.log(sortData(data, 'future'));

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

The issue with the tutorial is regarding the addHero function and determining the source of the new id

Whenever I need to introduce a new superhero character, I will utilize the add(string) function found in heroes/heroes.component.ts add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({ name } as H ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value ...

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 ...

Navigating through different components in Angular 4 using a service for routing

Encountering an issue while connecting my Angular 4 and REST application with a service. Here's the error message: compiler.es5.js:1694 Uncaught Error: Can't resolve all parameters for TypeaheadComponent: (?, [object Object], [object Object]). ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

How to Set Focus on an Input Field in an Angular 2 Modal

I'm currently working with modals in an angular project and I have a requirement to focus on a specific field within the modal. This particular field is a part of a @component: Autocomplete.html <div #autocomplete> <input #input requ ...

Navigating through Objects in Angular 9

I am facing a challenge in Angular 9/Typescript while trying to iterate through the object response from my JSON data. Despite searching for solutions, I haven't found any that work for me. In my JSON, there is a section called "details" which contain ...

What is the best way to duplicate a Typescript class object while making changes to specific properties?

I have a Typescript cat class: class Kitty { constructor( public name: string, public age: number, public color: string ) {} } const mittens = new Kitty('Mittens', 5, 'gray') Now I want to create a clone of the inst ...

Object autofill - Typescript utilizing Angular 5

I am working with an object called "features." Here is an example of the object: [{"_id":"5af03d95c4c18d16255b5ac7","name":"Feature 1","description":"<p>Description</p>\n","neworchange":"new","releaseId":"5aead2d6b28715733166e59a","produc ...

What are the steps to troubleshoot server-side TypeScript code in NextJS with WebStorm?

I am struggling to debug the NextJS API in WebStorm while using TypeScript and navigating through the app route. It is proving to be quite challenging to efficiently debug the API without relying heavily on console.log(). ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Safeguarding user data across all components is facilitated by Angular 2

My Angular2 app uses OAuth2 with password grant type for authentication. I currently store the session token on sessionStorage, but I need to securely store additional data such as user roles. While I am aware that sessionStorage or localStorage can be ea ...

Navigating back to the login page in your Ionic V2 application can be achieved by utilizing the `this.nav

Running into an issue with navigating back to the login screen using Ionic V2. Started with the V2 tabs template but added a custom login page, setting rootPage = LoginPage; in app.components.ts. When the login promise is successful, I used this.nav.setR ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response. [{"profi ...