Utilize JavaScript array to filter, match, and perform calculations based on dates and names

I am working with the following dataset:

const data = [
  {
    "employee_name": "Employee A",
    "commission_date": "14/05/2018",
    "commission_price": 9000
  },
  {
    "employee_name": "Employee A",
    "commission_date": "17/05/2018",
    "commission_price": 5000
  },
  {
    "employee_name": "Employee B",
    "commission_date": "18/05/2018",
    "commission_price": 2000
  },
  {
    "employee_name": "Employee B",
    "commission_date": "18/05/2018",
    "commission_price": 5000
  },
  {
    "employee_name": "Employee B",
    "commission_date": "19/05/2018",
    "commission_price": 500
  }
]

I need to calculate the total commission_price based on matching employee_name and commission_date.

The expected output should be:

[
  {
    "employee_name": "Employee A",
    "commission_date": "14/05/2018",
    "commission_price": 9000
  },
  {
    "employee_name": "Employee A",
    "commission_date": "17/05/2018",
    "commission_price": 5000
  },
  {
    "employee_name": "Employee B",
    "commission_date": "18/05/2018",
    "commission_price": 7000
  },
  {
    "employee_name": "Employee B",
    "commission_date": "19/05/2018",
    "commission_price": 500
  }
]

I have attempted to implement a solution using code from similar questions, but the results are only grouped by employee_name. Here is the code snippet I used:

let result = Object.values(data.reduce((r, { employee_name, commission_price }) => {
  r[employee_name] = r[employee_name] || { employee_name, commission_price : 0 }
  r[employee_name].commission_price += commission_price
  return r
}, {}))

Thank you.

Answer №1

If you want to handle multiple groups efficiently, consider using a combined key approach.

var data = [{ employee_name: "Employee A", commission_date: "14/05/2018", commission_price: 9000 }, { employee_name: "Employee A", commission_date: "17/05/2018", commission_price: 5000 }, { employee_name: "Employee B", commission_date: "18/05/2018", commission_price: 2000 }, { employee_name: "Employee B", commission_date: "18/05/2018", commission_price: 5000 }, { employee_name: "Employee B", commission_date: "19/05/2018", commission_price: 500 }], 
    result = Object.values(data.reduce((r, o) => {
        var key = ['employee_name', 'commission_date'].map(k => o[k]).join('|');
        r[key] = r[key] || { employee_name: o.employee_name, commission_date: o.commission_date, commission_price : 0 };
        r[key].commission_price += o.commission_price;
        return r;
    }, {}));

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

Arranging search findings based on relevance using javascript

I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first ...

Ways to Execute the Constructor or ngOnInit Multiple Times

Here's the scenario I'm facing: I have developed an app with multiple screens. One of these screens displays a list of articles. When a user clicks on an article, they are directed to another screen that shows the details of that specific item. ...

Record details to text file after the button is clicked on ASP.NET

My goal is to save an integer value (incremented each time a button is pressed) into a .txt file for each individual. However, I am struggling with how to store the value of each person's button click. I have a method in mind, but I need assistance wi ...

Accessing Elements by Class Name

I've been searching for information on the capabilities of getElementsByClassName for hours. While some sources mention it returns an HTML collection of items, length, and named items, w3schools provides an example where innerHTML is utilized: var x ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

How can I enable two-finger scrolling on mobile web browsers?

I am currently tackling a project that involves dragging operations on a canvas, making scrolling with a single finger impractical. My goal is to enable scrolling using two fingers instead. After testing different touch-action values, I discovered that pi ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

Troubleshooting Vue.js Error: Uncaught ReferenceError - jQuery Undefined

I'm a beginner with Vue.js and I'm attempting to develop a custom component that utilizes the jQuery formBuilder plugin from formBuilder. However, when I try to include this component file within another component, an error occurs: Uncaught Re ...

Using data fetched from PHP in HTML via jQuery post: A step-by-step guide

I have created a function in jQuery that uses $.post to send data to a PHP file. The query in the PHP file is working fine and returning the data back successfully. JavaScript code: function send_agenda_data(cidade_data){ var data = {'cidade_dat ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Trigger an AJAX request to execute a PHP script when a button is clicked

When I click a button, I want to run an ajax function that calls a PHP script and displays the resulting data under a specific div. However, it is not currently working as expected. Upon checking the console, I noticed that no value is being passed to the ...

How can I create a custom validator in Angular 2 that trims the input fields?

As a newcomer to Angular, I am looking to create a custom validator that can trim the input field of a model-driven approach form. However, I have encountered difficulties during implementation. When attempting to set the value using setValue() within th ...

Is there a way to use JavaScript to change the text displayed in this ASPX control?

On an ASPX page, I have the following input control: <input tabindex="0" class="_f_ql _f_rl textbox allowTextSelection placeholderText" role="textbox" aria-labelledby="MailCompose.SubjectWellLabel" autoid="_f_B2"></input> I am limited to inje ...

MUI: How can I resolve the issue of TextField not supporting the number type with maxLength restriction?

I am currently facing an issue with applying maxLength to the TextField component when the type is set to number. Here is my code snippet: const CustomTextField = ({ label, value, maxLength, required, disabled, handleChange, ha ...

``Please note that the Sinon spy.called method is currently not

Context In my setup, a small server receives data from a machine. Each time a message is received, a function in a dispatcher object is called, which simply logs everything it receives to the console. Issue While I can see the logs in the console, Sinon ...

Avoid an excessive number of XHR/AJAX requests when using the Facebook embedded iframe

I am facing an issue with a Bootstrap Carousel that contains multiple social embeds from Facebook, all of which have videos. The problem is evident on this simple jsfiddle due to the Facebook embed. If you visit this page: https://jsfiddle.net/1L95vqn4/, ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...