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

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...

Creating obstacles in a canvas can add an extra layer of challenges and

I am working on creating a basic platformer game using the code displayed below. window.onload = function(){ var canvas = document.getElementById('game'); var ctx = canvas.getContext("2d"); var rightKeyPress = false; var leftKeyPress = false; ...

Issue with Stack Divider not appearing on Chakra UI card

I'm currently designing a card element using Chakra UI. However, I've noticed that the Stack Divider in the Card Body isn't displaying as expected. Is there a specific way it needs to be structured for it to show up? For example, should I se ...

What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this: MyModule = angular.module('MyModule', ['dependency1', 'dependency2']); MyModule.factory('MyService', ['$other ...

Issues with displaying public images in Next.js production build are being reported

My Next.js app is deployed on Heroku. Images show up when I develop locally, but once pushed to Heroku and checked on the live site, the images return a 404 error. The images (.png) are stored in a public folder within my project, and I reference them in t ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Encountered a 404 error when attempting to deploy create-react-app due to failed resource loading

Any assistance would be greatly appreciated. Thank you! Although my website runs smoothly locally, I am encountering issues when trying to deploy it in a production environment. Upon executing npm run deploy, the expected outcome is an automatic build for ...

Communicating with my own account through Nodemailer

I have successfully set up nodemailer locally to handle email functionalities on my website. The goal is for it to extract the user's email input from an HTML form and then forward it to my Gmail account through a contact form. <form action="http: ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

Encountering an "Unspecified Reference Error" while attempting to retrieve data from an API in your

I've been attempting to utilize a mock API from in order to fetch data for my Next.js application. However, I am consistently encountering an undefined reference error, despite following the code snippet provided in the official Next.js documentation ...

Error encountered: Unexpected syntax error found in jQuery ajax call

I am attempting to send a simple request to Instagram using the code snippet below: $.getJSON("https://www.instagram.com/kidsfromthe90sband/media/?callback=?", function(data) { alert(JSON.stringify(data)); }); http://jsfiddle.net/FPhcr/731/ ...

Passing a property to a click event handler in ES6 with React: What's the best approach?

Struggling with passing props to a click function in my React learning journey. I'm attempting to make a basic ES6 counter component that increases when a button is clicked. The click function I have so far is: click() { this.setState({ c ...

Best method to generate an element using any jQuery selector string

What I want to accomplish I am looking to create an element that matches any given selector string. Here's a quick example: var targetString = "a.exaggerated#selector[data-myattr='data-here']"; var targetEl = $(targetString); if(!targetE ...

Combining two objects in node-red: A step-by-step guide

msg.payload : Object object HAMK307: object a_temperature: 23.1 a_humidity: 46 a_brightness: 3703.05 a_lights: "on" a_presence: "empty" r_temperature: 35.59 r_humidity: 30.46 r_pressure: 994.43 a_time: object ID: "HAMK-307" m ...

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

Exploring the connection between Django and AngularJS: delving into the router functionality and how Django variables are assigned

As a beginner in IONIC, AngularJS, and Django, I recently attempted to host an IONIC project within Django. While both Django and AngularJS are excellent frameworks individually, integrating them has left me feeling confused. Question 1: How can I effecti ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: When a customer se ...