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

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

React components multiplying with every click, tripling or even quadrupling in number

My app enables users to create channels/chatrooms for communication. I have implemented a feature where pressing a button triggers the creation of a channel, using the function: onCreateChannel. Upon calling this function, the state of createChannel chan ...

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

When triggering the fireEvent.mouseOver event, it seems that document.createRange is not a valid

Having trouble using fireClick.mouseOver(tab) to test tooltip functionality on tab hover. Here's a snippet of the code: it('should handle change on hover of tab', () => { const {getByTestId, getByRole} = renderComponent('Dra ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Steps for connecting an external .otf file in p5.js

I'm struggling to connect a custom font file to my p5.js sketch through a URL in order to upload it on codepen.io. Unfortunately, the font is not available on Google Fonts. I attempted to include the URL in the load font function like this: loadFon ...

Include a new route in the Vue.js router dynamically during runtime

I am in the process of developing an application and I want to incorporate extensions into it. These extensions will have their own Vue components, views, and routes. Instead of rebuilding the entire app, I am looking for a way to dynamically add these new ...

An easy method for declaring a 2D array in C++

Looking to create a 2-dimensional array in c++ where the dimensions are provided by the user. What is the best method for defining an int 2-dimensional array in c++? I came across a solution that involves defining a 1-dimensional array and then creating ot ...

Resolving the Enigma: Querying jQuery for Real-Time Validation and

I'm fairly new to jQuery and I'm facing a challenge in my registration form script. Specifically, I want to check if the entered username or email is already taken while the user is typing. Currently, this functionality works by making a json req ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

Deleting and inserting an element in the Document Object Model

I am currently working on developing a framework and need to create a directive called cp-if. Unlike the existing cp-show directive, where I can simply change the visibility of an element to 'none' and then make it visible again, with the cp-if d ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

extracting both the value and ID attributes from a RadioButtonGroup component in React MaterialUI

I am currently working on extracting the selected value and gameID from a dynamic MaterialUI RadioButtonGroup. Although I have been successful in retrieving the gameID, I am encountering difficulty in obtaining the value: <form onSubmit={this.handl ...

What is the best way to assign the selected attribute to my mat-option element?

I am encountering an issue with my mat-select and mat-option control. I am trying to apply the selected attribute to the first mat-option control without using binding on [(ngModel)] or [(value)]. The mat-option control is being generated by the *ngFor d ...

What steps can be taken to convert this function into a more concise, dry function?

I'm attempting to customize a typewriter effect on my webpage, and while it successfully displays predefined data, I am struggling with converting it into a function that can receive values and then display those values. I have made attempts to modif ...

Switching players every two turns in a JavaScript AngularJS game

I have implemented an AngularJS score keeping game where players switch every two turns. The code works for one round, but I want to create a loop that keeps switching players. Check out my code below: app.controller('EventController', function( ...

Can anyone help me with integrating a search functionality inside a select tag?

I am working on a select dropdown and want to add a search box to easily filter through the available options. I know this can be done using the chosen library, but I prefer to implement it using plain JavaScript or jQuery. Does anyone have suggestions on ...