Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData

[0] object 
amount: 29.9
code: "012"
currency: "BRL"
payedDate: "2016-11-10"
roDate: "2016-08-01"
type:"OTHER"

[1] object
amount: 39.9
code: "013"
currency: "BRL"
payedDate: "2016-11-11"
roDate: "2016-08-01"
type:"OTHER"

I'm trying to figure out how to calculate the total sum of the amounts in order to store it in a variable. For example, the total should be 69.8

<span> {{ totalOfSumAmount }} </span>

Answer №1

The most convenient solution is to create a custom function that automates this task.

<span> {{ calculateTotalAmount() }} </span>

Integrate the function into your controller:

$scope.calculateTotalAmount = function () {
    var totalAmount = 0;
    for (var i = 0; i < $scope.otherDetailsData.length; i++) {
        totalAmount += $scope.otherDetailsData[i].amount;
    }
    return totalAmount;
}

Answer №2

One way to achieve this is by utilizing the Array.prototype.reduce method:

$scope.sumOfAmounts = $scope.dataToReduce.reduce(function(previousValue, item) {
  return previousValue + item.amount;
}, 0);

Answer №3

Utilize the array.reduce() method for summing up the results. Here's an example:

    $scope.totalOfSumAmount =   $scope.items.reduce(function(carry, currentItem) {
      //add the amount from the current item to the running total (carry)
      return carry + currentItem.amount;
    }, 0);//0 represents the initial value

The callback function (i.e.

function(carry, currentItem) {...
in the example) can actually accept four parameters:

  • previous value - the value from the previous iteration (or the initial value)
  • current value - the current element in the array
  • current index - the current index of the current element in the array
  • original array - the array being iterated over

The second parameter (optional) is the initial value, so if you need to start with a value other than 0, you can pass that instead.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.items = [{
      amount: 29.9,
      code: "012",
      currency: "BRL",
      payedDate: "2016-11-10",
      roDate: "2016-08-01",
      type: "OTHER"
    }, {
      amount: 39.9,
      code: "013",
      currency: "BRL",
      payedDate: "2016-11-11",
      roDate: "2016-08-01",
      type: "OTHER",
    }];
    $scope.totalOfSumAmount =   $scope.items.reduce(function(carry, currentItem) {
      //add the amount from the current item to the running total (carry)
      return carry + currentItem.amount;
    }, 0);//0 is the initial value
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Total: <span> {{ totalOfSumAmount }} </span>
  </div>

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

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Chronological Overview (Highcharts)

Can you customize a timeline in Highcharts to resemble the image? https://i.sstatic.net/5Lipu.png I have a functional example of the timeline I desire, but the color coding and filtering aspects are challenging for me. I am attempting to apply a filter th ...

Incorporating server-side rendered components into a Vue.js parent component

I have a server-side rendered page that includes information about "orders" and a root Vue object initialized as the "parent object." Is it feasible to assign the rendered HTML orders as children of that parent Vue object? Vue.js is known for its dynamic ...

Scale up each image with the use of Java script

I have a main container with three different sub-containers, each containing an image and text. I want to achieve the effect of zooming in on the image of the specific sub-container when hovering over it. Currently, when I hover over any sub-container, all ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

I want to show a string array in the ui-grid, with each ui-grid displaying a single row for each string in the array

I am trying to showcase each piece of data from an array in its own individual ui-grid row. Can someone please assist me in verifying if this approach is correct? For example, I want data[0] to be displayed in one ui-grid, and data[1] in another ui-grid, c ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Ensure the browser stays anchored at the bottom of the page while employing jQuery to reveal a div

This piece of code allows me to toggle the visibility of a div: <a href="#" class="show_hide">Show/hide</a> <div class="slidingDiv"> My content...... <a href="#" class="show_hide">hide</a></div> <script src="http:// ...

Leverage the URL parameter with variables in HTML using AngularJS

I'm facing the same issue as yesterday: trying to extract and utilize parameters from the URL within my HTML page using AngularJS. What am I doing wrong? The parameter I need to work with is: https://url.com/index.html?user I aim to retrieve the "u ...

The method's title does not correspond to a function

I am having difficulty calling the method within my module. An error occurred: TypeError: usr.User.getAddress is not a function I am unsure of how to resolve this issue, as I suspect there may be a problem in my module code. My goal is to retrieve the ad ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

Comparing the efficiency of Jquery draggable with thousands of elements versus updating the elements continuously

Currently, I am developing an application that involves dragging an image using Jquery's draggable utility. The image is accompanied by several overlay divs containing various components positioned based on pixel locations, sometimes reaching into the ...

Resolving issues with PHP JSON format error in array formatting

This is the MySQL script I am working with: $result = mysql_query("SELECT users.*,games.game_names,games.id AS games_id FROM users LEFT JOIN games ON FIND_IN_SET(games.id,users.games)") or die(mysql_error()); while($user = mysql_fetch_array($result, MY ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

Sorting a collection of objects into separate arrays

When working with React, here is an example of the state configuration I am using: state = { Producers: [], France: [], Spain: [], Germany: [], Portugal: [], Greece: [], Austria: [], isLoading: false }; I ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

Creating an interactive quiz using JSON and distributing the results from a SQL query into a multidimensional array

Working on a quiz system that stores questions and answers in a MySQL database has led me to try and convert the data into a multidimensional array and then into JSON format. However, the result is not meeting my expectations and I'm stuck with the cu ...

Steps for dynamically loading the content of a Bootstrap 4 Modal

I am currently in the process of developing a website that will showcase a wide range of images. The design is set up as a landing page with all content contained within the main HTML page - there is only an index.html file for now. This website will serv ...

Padding an array with zeros along a specific axis

I need to pad the following array: [[1, 2] [3, 4]] so that it becomes: [[0, 0, 0] [0, 1, 2] [0, 3, 4]] I can easily achieve this with vstack and hsrack when working with a 2D input. However, I encounter an issue when adding an extra dimension to re ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...