Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column:

receiptsByDate: function(){
   let byDate = _.groupBy(this.receipts, 'date');
   let totals = {};
   _.forEach(byDate, function(amounts, Date){
   totals[Date] = _.reduce( byDate[Date], function(sum, receipt){
   return sum + parseFloat( receipt.total );
   }, 0);
   })
   return totals;   
}

This function creates an object in the format of date: total.

Example of a receipt on which this function is applied:

card_commission:null
created_at:"2019-11-14 06:13:20"
customer_id:null
date:"2019-11-14"
discount:"12000.0"
id:1
location_id:null
number:"2019-00001"
service:null
subtotal:"200000.0"
table_id:null
taxes:null
ticket_id:1
total:"188000.0"
updated_at:"2019-11-14 06:13:20"

However, I now need to not only group by date but also calculate sums for other columns such as discount, subtotal, and so on. After searching online, I couldn't find a solution for this specific requirement. Can anyone provide guidance or suggest an alternative approach? It doesn't necessarily have to involve loadash; any other solution would be greatly appreciated.

Answer №1

Instead of simply providing the total value, consider returning an object that includes all calculated values for each specific date.

salesByDate: function(){
  let byDate = _.groupBy(this.sales, 'date');

  let calculatedData = {};
  _.forEach(byDate, function(salesList, date){
    calculatedData[date] = {
      totalSales: _.sumBy(salesList, function(sale) {
        return parseFloat(sale.total);
      }),
      discountApplied: _.sumBy(salesList, function(sale) {
        return parseFloat(sale.discount);
      })
    }
  };

  return calculatedData;
}

Answer №2

Try using a different approach than reduce by utilizing forEach instead. Consider assigning Date as the key for an alternative method.

let summary = {}
_.forEach(byDate[Date], (receipt) => {
   if(summary.total == null)
      summary.total = parseFloat(receipt.total)
   else
      summary.total += parseFloat(receipt.total)

   if(summary.other== null)
      summary.other= parseFloat(receipt.other)
   else
      summary.other+= parseFloat(receipt.other)
}
totals[Date] = summary

To enhance your code, you may want to replace 0 with { total: 0, other: 0} and perform calculations within the forEach function instead of using reduce.

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

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Updating data in a SQL database using PHP when a button is clicked

This Question was created to address a previous issue where I had multiple questions instead of focusing on one specific question Objective When the user selects three variables to access data, they should be able to click a button to modify one aspect o ...

What is the reason for not being able to locate the controller of the necessary directive within AngularJS?

A couple of angularjs directives were written, with one being nested inside the other. Here are the scripts for the directives: module.directive('foo', [ '$log', function($log) { return { restrict: 'E', r ...

Creating a new object in an empty array within my profile model (mongodb/mongoose) is simple. Just follow these steps to successfully add a

Presenting my Profile model: const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, company: String, website: String, location: String, status: { type: String, require ...

Retrieve Element By Class Name in JavaScript

How can I modify the border color at the bottom of the .arrow_box:after? Javascript Solution document.getElementsByClassName("arrow_box:after")[0].style.borderBottomColor = "blue"; Despite trying this solution, it seems to be ineffective! For a closer ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Automatically rehydrate an instance using Angular and JavaScript

REVISION Special thanks to Shaun Scovill for providing an elegant solution using lodash // Creating an instance and injecting server object - within the ChartService implementation below var chart = new Chart(serverChartObject); // Replacing ...

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

Encountered an issue with AWS S3: unable to retrieve the certificate from the local issuer

After completing my Protractor test suite execution, I am encountering an error while trying to upload my HTML result file to AWS S3 using JavaScript in my automation script. Can someone assist me in resolving this issue? static uploadtoS3() { con ...

Transferring data via AJAX technology

My goal is to empower the ability to upload files using AJAX. I attempted to utilize (JavaScript) in this manner: $("input[type='file']").change(function(){ var file = document.getElementById("uploadelement").files[0]; $.ajax ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

Send nodejs express static request over to secure https server

Is there a way to ensure all HTTP requests, including those for static files, are redirected to HTTPS? This is the code I currently have: app.use(express.static(__dirname + '/public')); app.get('*', function(req, res) { if (!req. ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...