Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time.

This is how I retrieve the data:
 function getEndTasks() {
        $http.get('db_files/endTasksDB.php').then(function(response) {
            $scope.dates = response.data;
            console.log($scope.dates);
        })
    }

The console log displays:

Array[10] 0 : Object 1 : Object 2 : Object 3 : Object 4 : Object 5 : Object 6 : Object 7 : Object 8 : Object 9 : Object

Object 0:

Object
$$hashKey:"object:60"
deadline:"2017-02-28"
dept:"test"
id:"1"
priority:null
status:"Closed"
task:"test"
task_end:"2017-03-02 10:57:51"
task_start:"2017-02-27 14:45:53"
task_time:"83"
total_time:"null"
username:"Nelson"

This is what I have tried:

 $scope.total = response.data.map(function(item) {
                var totalTime = 0;

                for (var i=0; i<(item.task_time).length;i++){
                    totalTime = item.task_time[i];
                    totalTime += totalTime;
            item.total_time = totalTime;
            console.log("total time: " +item.total_time);
                    }
                return item;
            })

No errors are thrown, but the console log displays:

total time: 88 total time: 33 total time: 99 total time: 00 etc

and here is the table where I want to display it:

<table md-table>
    <thead md-head md-order="sort.order">
        <tr md-row>
            <th md-column>Spółka</th>
            <th md-column>Łączny czas</th>
        </tr>
    </thead>
    <tbody md-body>
        <tr md-row md-select="totalTime" md-on-select="" md-auto-select ng-repeat="totalTime in total | orderBy:sort.order | filter:search">
            <td md-cell>{{ totalTime.dept }}</td>
            <td md-cell>{{ totalTime.total_time }} godzin</td>
            </td>
        </tr>
    </tbody>
</table>

Answer №1

There are a number of issues to address here. Firstly, you've got an array of data structured like this: (simplified)

var data = [{
  dept:"test",
  task_time:"83"
},{
  dept:"test",
  task_time:"41"
},{
  dept:"other",
  task_time:"10"
}];

If you want to calculate the total time taken for all tasks, you would do:

var total = 0;
angular.forEach(data, function(item) {
  total += parseFloat(item.task_time);
});

console.log(total) //will output 134

To sum the total based on department, you could store it in an object like this:

var totalPerDept = {};
angular.forEach(data, function(item) {
  if(!totalPerDept[item.dept]) {
    totalPerDept[item.dept] = 0;
  }
  totalPerDept[item.dept] += parseFloat(item.task_time);
});

In the view, you would display it like so:

<div ng-repeat="d in data">
 Department: {{d.dept}} | Total in this dept: {{totalPerDept[d.dept]}}
</div>

This approach uses the department name as an index to access properties from another object.

However, handling these calculations directly within the query may provide a more efficient solution overall.

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

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

Enhancing Performance with ngView in AngularJS and Retaining Data in Memory

Working on my project, I have been utilizing AngularJS along with ngView. While ngView functions seamlessly in conjunction with ngRoute, I have encountered a situation where upon returning to the previous link, ngView reloads the data again through Ajax. ...

How to send a PHP variable to Ajax and execute a corresponding PHP function in response

I have a set of database records that are being displayed in separate div elements on the page. Each record corresponds to a specific ID, with its information displayed inside the div. My goal is to create a delete button for each record that would allow ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

Is there a way to avoid adding this final "faulty state" to the array?

While working on dynamically slicing an array, I noticed that my while loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop(), I am curious ...

Is it possible to generate a specified number of divs or HTML tags with varying information using ReactJS?

Currently, I am in the process of constructing this website and I have noticed that I have 4 divs that are essentially doing the same thing. However, I find myself copying and pasting these divs 4 times, only making minor changes to 4 bits of information. ...

Tips for transferring data using the GET method from the client side to the server side via AJAX

I am attempting to send two dates - a start date and an end date, in order to retrieve data between those two dates. However, my current implementation is not working as expected. $(document).ready(function(){ const date_inputs = new FormData(); ...

jQuery Form: Despite the Ajax response being visible on the page, it does not appear in the source code

Utilizing Jquery Form for an Ajax image upload. This is the relevant HTML code: <div class="input_con imageupload_con"> <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> < ...

Data cannot be displayed in a grid using Kendo UI and AngularJS within an ASP.NET MVC framework

Currently utilizing KendoUI and AngularJS in my ASP.NET MVC 4 project. I am attempting to retrieve data from the database and display it in a grid, but unfortunately, the grid is not showing any data. The data has been successfully downloaded from the db a ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

Layout display issue post redirection in React

I am facing an issue with my app that utilizes styled-components and material-ui. I have set up private routes based on user roles, and when a non-authenticated user is redirected to the login page, the layout fails to load properly. App.tsx import React ...

Error: The object being referenced (scope.awesomeThings) is undefined and unable to be evaluated

Each time I run the grunt test command, I encounter this error. I set up a project using yo angular and attempted to execute the example code provided in Yeoman's scaffold. Something seems to have gone awry here - below is the code snippet that I trie ...

Setting up Babel to effectively function across multiple directories

I've been utilizing Babel for some time now and it effectively transforms my ES Next code to the dist directory using this command: babel src --out-dir dist --source-maps --copy-files Up until now, all my JavaScript code has been stored in the src fo ...

What is the best way to manage a download link that necessitates an Authorization token when using Angular?

I'm currently working with a REST API in combination with Angular. The issue I'm facing is related to post objects that include file attachments. Every time a user wants to download a file attachment, they must make a call to /get/file/{id}, but ...

The AngularJS model does not reflect changes after I make edits in the editor

Currently, I am utilizing Jhtmlarea and have created a custom directive as follows: test.directive('jhtml', function () { return { restrict: 'A', replace: false, link: function (s ...

The issue arises when the Javascript function is triggered twice, resulting in only 3 out of 4

I'm currently working on a JavaScript calculator project. Everything is running smoothly except for the add() function (subtraction, multiplication, and division are all functioning properly). Additionally, when I hit "=" it displays the answer twice ...

Does vite handle module imports differently during development versus production?

I am currently working on incorporating the jointjs library into a Vue application. It is being declared as a global property in Vue and then modified accordingly. Below is a basic example of what I am trying to achieve: import Vue from 'vue'; im ...

I'm perplexed by setting up Node.js in order to work with Angular.js

Currently following the Angular tutorial provided at https://docs.angularjs.org/tutorial, but I'm encountering confusion with the Node.js installation. Having already installed node globally on my Mac, the tutorial mentions: The tutorial instructio ...

Having difficulty grasping the concept of using unicode characters with canvas fillText

I am attempting to showcase special characters in a font using the canvas fillText feature. The code I am employing is as follows: canvas = document.getElementById("mycanvas"); context = canvas.getContext("2d"); hexstring = "\u00A9"; //hexstring = " ...