Calculating the total of an array's values using JavaScript

Receiving information from an API and looking to aggregate the values it contains. Consider the following code snippet:

function totalPesos(){
    $http.get('/api/valueForTest')
    .then(function(data){
        $scope.resumePesos = data.data.Response;
        //console.log($scope.resumePesos);
}

The response retrieved is:

[{Id: 60, Name: Chuck, Quantity: 300},
{Id: 61, Name: Arthur, Quantity: 199},
{Id: 62, Name: John, Quantity: 450}]

The goal is to sum the Quantity. How can this be achieved? An attempt with the following code was made:

$scope.resumePesos.reduce(function(a,b){return a + b; });

However, the result obtained was [object Object]

Answer №1

Experiment with the following JavaScript code snippet:

let items = [{Id: 60, Name: 'Chuck', Quantity: 300},
{Id: 61, Name: 'Arthur', Quantity: 199},
{Id: 62, Name: 'John', Quantity: 450}]
let totalQuantity = items.reduce(function(sum, currentItem){
  sum += currentItem['Quantity'];
  return sum;
},0)
console.log(totalQuantity);

Answer №2

If I were to rephrase it, it would go something like this:

const totalQuantity = $scope.resumePesos.reduce((accumulator, currentItem) => accumulator + currentItem.Quantity, 0);

Keep in mind that when using the reduce method, the first parameter in the function is the accumulator and the second parameter is each value being iterated over, which in this scenario is each object. Therefore, you must access the Quantity property of each object. Additionally, make sure to provide 0 as the initial value for the accumulator in the reduce method since we want a numerical result.

Answer №3

Here is an alternative approach you can consider:

$scope.resumePesos.reduce((x,y) => {return x + y.Quantity}, 0); // Remember to include 0 at the end

Answer №4

There are two errors you need to address here - first, make sure to initialize a starting value for the reduce function and secondly, ensure that you are summing up the numerical property of the object (.Quantity) rather than the object itself.

 var total = $scope.totalAmount.reduce(function(sum, item) {
    return sum + item.Quantity; 
 }, 0);

Answer №5


The Solution

$scope.total = $scope.resumePesos.reduce(function(a,b){return a + b.Quantity; }, 0);

Answer №6

If you're looking to incorporate additional functions into your project, consider utilizing lodash for added functionality.

For example:

_.sumBy($scope.resumePesos, 'Quantity');

var data = [
  {Id: 60, Name: 'Chuck', Quantity: 300},
  {Id: 61, Name: 'Arthur', Quantity: 199},
  {Id: 62, Name: 'John', Quantity: 450}
]
  
console.log(_.sumBy(data, 'Quantity'));
  
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №7

Thank you to everyone who provided suggestions, I followed your advice and it worked perfectly!

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 Node API is unresponsive when using Postman or accessing through the browser, as it is not returning any status code. However, no errors are displayed when

I am currently working on developing a Node API for an employee department model. I have created various requests such as 'GET', 'PUSH', 'PATCH', and 'DELETE' for both the employee and department endpoints. This deve ...

What steps should I take to modify the URL using the SELECT tag?

Having a bunch of SELECT tags in place <select id="url"> <option id="url1" >url 1</option> <option id="url2" >url 2</option> </select> <button onclick="go()">GO</button> Followed by the associated scrip ...

The play button on the iOS video player will be deactivated automatically after watching 15 videos

I have developed an application using the Ionic Framework that includes multiple videos for playback. To organize these videos, I created a category system where users can click on a video title to access the corresponding video player page. The video pla ...

The underscore (_) parameter in HTTP GET requests

Lately, I've been seeing the '_' parameter on many websites with a seemingly random string attached to it. For example: website.com/?_=98765432 Can someone explain the significance of this parameter and how these numbers are generated? ...

Exploring the world of unit testing for Sails JS 1.0 helper functions

Currently, I am in the process of setting up unit testing for my SailsJS 1.0 application. My goal is to simulate the DB without needing to execute 'sails lift' to run tests. In my application, there is a straightforward actions2 (node machine) h ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

What is the reason that the attr function fails to function in this particular scenario?

I want to implement a functionality where clicking on an input field clears its value, but I can't seem to make it work. Here is the HTML code: <input id='input' type="text" name="phppostvar" value="clear this"></input> This i ...

Make sure to pay attention to the messageCreate event within a direct message channel on discord

I've come across this question repeatedly, and despite trying numerous suggestions, I still can't seem to make it work. Currently, I'm resorting to logging the messageCreate event, but unfortunately, that isn't yielding any results. Any ...

Javascript animation functioning for a singular item within a list

As I continue practicing my skills in Javascript and HTML, I stumbled upon this intriguing list known as "item/adapter", similar to what we refer to as adapters in Android. While the process of adding them programmatically to my div is working smoothly, I& ...

Creating a dataset for D3 in JavaScript: A step-by-step guide

I am attempting to construct a graph similar to this: https://i.sstatic.net/USdyj.png. The graph represents a dependencies tree where each node has a list of elements it depends on as children (in a list), or a simple JSON structure with name and size info ...

Change the class of multiple elements using jQuery with a set time interval

Here is a clever jQuery snippet I've put together to toggle the class of an element at intervals: setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800); The code runs smoothly! However, I now have multi ...

Are there options available in nightwatchjs for making intricate decisions with selectors?

When using the NightWatch JavaScript Selenium tool, it is important to establish good practices for identifying different parts of the GUI before running tests. For example, distinguishing between options A and B and creating separate tests accordingly. An ...

Using React: Passing the state value of Child1 to the Parent component, then passing it back down to Child2 from

Within my application, I've implemented two child components: 'FoodScreen' and 'OperationScreen', along with a parent component called 'Desk'. I am passing a JSON array variable to the FoodScreen component in order to sel ...

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

What is the best way to dynamically generate dependent dropdown lists in AngularJS?

Currently, I am involved in a project where I utilized the following link to populate specific dropdown menus. My goal is to have dynamically dependent dropdown lists that can be used as filters. While I came across some references for dependent dropdown l ...

Issues arising with shadows in THREE.js

I've been struggling to get shadows to work in this fiddle despite trying various configurations. I've looked at other similar questions, tried all the suggested solutions, but still nothing... My current settings include: this._box.castShadows ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results ...