Perform the multiplication operation on two values retrieved from the API response and then calculate the total sum

I am currently pulling information from an API and I'm looking to perform a calculation on the data. Specifically, I want to multiply two different values from the response and then sum up the totals. While I already know how to sum all the values using reduce:

        function getHistoricSales(){
         $http.get('api/SomeApi')
         .then(function(data){
            $scope.salesResult = data.data.Response;

                var hResults = $scope.salesResult.reduce((a, b) => a + b.Cost, 0);
                $scope.historic = hResult.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
               });
            }

However, if for example, the response includes not just the Cost (b.Cost), but also the Quantity. So, my question is how can I first multiply each Cost by its corresponding Quantity, and then sum the results?

I am working with JavaScript and AngularJS.

Any help would be greatly appreciated. Thank you in advance...

Answer №1

It seems like the solution you're seeking is:

let totalCost = $scope.salesResult
                       .map(sr => sr.Cost * sr.Quantity)
                       .reduce((a, b) => a + b);

This code snippet will calculate the total cost of each sales result by multiplying the cost and quantity, then summing them up.

Here's an example to illustrate this process:

const data = [
 {Cost: 10, Quantity: 15},
 {Cost: 5, Quantity: 11},
 {Cost: 2, Quantity: 110},
 {Cost: 5, Quantity: 90},
]

const result = data
              .map(sr => sr.Cost * sr.Quantity)
              .reduce((a, b) => a + b);

console.log(result);

Answer №2

To ensure accurate calculations in the reduce() function for each item in $scope.salesResult, it's important to consider cases where a quantity property may be optional. By checking for and handling instances where the quantity is undefined, you can prevent errors caused by multiplying by an undefined value.

var salesResult = [
  // Some items only have the cost
  { cost: 10 },
  { cost: 10 },
  // Some items might also have a quantity
  { cost: 10, quantity: 10 },
  { cost: 10, quantity: 10 },
];

var hResults = salesResult.reduce((total, result) =>
  total + (result.quantity
    ? result.cost * result.quantity
    : result.cost), 0);
    
console.log(hResults); // 220

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

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

Do I need to include $scope in my controller for this AngularJs?

I am attempting to replicate the functionality of this Plunker. Specifically, I want to add a button to each row in an ag-grid. function ageClicked(age) { window.alert("Age clicked: " + age); } function ageCellRendererFunc(params) { params.$scope ...

Is it possible to pass a variable as an input parameter in the Date constructor when creating a timestamp in Firebase

I'm looking to work with timestamp queries. Note: setSD and setED are part of the Vue object's data, and the firebase function call is within the method. callFirebase: function (){ let startdate = new Date(this.setSD+'T00:00:00&apo ...

Sending data through the backbone form?

Whenever the submit button is clicked, a post request should be made to the server with input data and it will return a JSON object. I am unsure where to define the success function and how to receive the response object. Is this the correct way to call a ...

Ways to simultaneously apply fade in and fade out effects using CSS

body { background-image: url("background.jpg"); background-attachment: fixed; font-family: 'Roboto', sans-serif; color: #333333; } #container { height: 1000px; } /* HEADER WITH NAVIGATION BAR AND LOGIN OPTION */ #head { position: abso ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...

The radio button is displaying the text 'on' instead of its designated value

function perform_global(tablecounter) { for (index = 1; index <= 2; ++index) { var dnsname = "dns_name"+index; oRadio = document.getElementsByName(dnsname); alert (" radio ID " + dnsname + " " + index + "length " + oRadio.leng ...

Maintaining the integrity of a list within a for loop

I have a challenge where I need to display 3 elements in cards on each row from a list of elements. The issue with my current code is that it only displays the first two elements and then the loop stops. Here is the code snippet using ReactJS and Materia ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...

When a custom icon is clicked in the vue-select dropdown, the custom method is not activated

In my current project, I am creating a vue-component based on vue-select. Within this component, I have added a custom info Icon. The issue I am facing is that when the user clicks on the Icon, instead of triggering my custom method getInfo, it opens the s ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

React - updating key prop does not trigger re-render of child component

I have implemented react-infinite-scroll to display a continuous feed of data. My goal is to refresh the data feed whenever the user makes any changes to their settings. To achieve this, I am utilizing a key prop for the InfiniteScroll component. The conc ...

Ways to stop Bootstrap collapse from displaying depending on a certain condition in bs5 framework

I've been struggling to figure out how to prevent a collapsible panel from opening or showing if a specific value is null. Despite multiple attempts, I haven't had any success. HTML <a href="#" data-bs-toggle="collapse" da ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Is there a way in Vue to switch between encrypted and unencrypted content in an input field?

I'm grappling with the challenge of creating an input field where the contents are initially hidden as 'ab****gh' and can be toggled to reveal as 'abcdefgh' upon a click. I've been experimenting with some code, but I'm st ...

I need a regex pattern that will only match numeric values

Looking for a regular expression that can extract only numbers from a string. Specifically, numbers not preceded by a character. For example: "(a/(b1/8))*100 In this case, we do not want to include b1. We are interested in retrieving numbers like 8, 100, ...

The callback keeps getting triggered repeatedly, and I'm struggling to understand the reason behind it

One of the challenges I am facing revolves around a utility function responsible for launching a child process. The goal is to halt the listening process and trigger the callback as soon as the child process outputs a specific message to stdout: export co ...

BlockUI - Uncaught error: The object does not contain the method 'blockUI'

Trying to implement the blockUI jQuery Plugin, I have added the necessary libraries in this way; <script src="http://malsup.com/jquery/block/jquery.blockUI.1.33.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...