Adding up characteristics within an array of objects using Angular

As someone who is relatively new to Angular and Javascript, I am reaching out for some assistance. My goal is to calculate the sum and average of values within an object array. The objects are added to the array via input boxes, and here is the code I have developed so far:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "", 
     phase: "", 
     date: "", 
     startTime: "", 
     intTime: "", 
     endTime: "", 
     comments: ""}
];

$scope.saveLog = function(){

    //CALCULATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});

The issue lies in the intSum function - where I aim to sum up the intTime properties of all the objects. For instance, if object1's intTime = 1, object2's intTime = 2, and object3's intTime = 3, the expected result from intSum should be 6. However, the current output from intSum is 123.

Any guidance on this matter would be highly appreciated!

Answer №1

Consider:

sum += parseInt($scope.logs[i].intTime);

As an alternative to:

sum += $scope.logs[i].intTime;

UPDATE: Exploring the implementation of the reduce function in JavaScript can provide a different approach to iterating over your array: https://www.w3schools.com/jsref/jsref_reduce.asp


UPDATE2: Make sure to initialize $scope.logs.intTime with "". The initial value being an empty string in the array may lead to generating NaN. I recommend initializing your array like this:

$scope.logs = [];

Answer №2

The intTime variable is stored as a String within your object. This means that when you perform addition operations on it, it is treated as string concatenation instead of numerical addition. To correct this issue, convert the intTime value to a Number using the parseInt function before performing any sums.

Answer №3

Consider utilizing parseInt while calculating the sum+= operation:

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += parseInt($scope.logs[i].intTime);
    }
    return sum;
};

Answer №4

  1. To convert the intTime from a string to an integer, you can utilize JavaScript's reduce() function.
  2. Here is how you can use the reduce() function in JavaScript:

    • arr.reduce(callback, [initialValue])
    • To define the callback function: function(accumulator, currentValue) { return accumulator + currentValue }
  3. For a practical example and implementation, check out this code snippet: http://jsfiddle.net/GruffBunny/4cFU3/

    • You can write your sum function like this:

      $scope.sum = function(items, prop){ 
          return items.reduce(function(a, b){
              return a + parseInt(b[prop]); 
          }, 0);  
      };
      
    • You can then call the function using
      $scope.sum($scope.logs, 'iniTime')
  4. Here are some useful references for further reading:

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

Retrieving a specific property from a SimpleXMLElement Object

As I couldn't find a solution to my specific case, please refrain from marking this as a duplicate. I have an XML response in SOAP format, which I am storing in an object using the following code: $resultObj = SimpleXML_Load_String($xml); If I use ...

In TypeScript, what is the method to specifically retrieve only resolved Promises while disregarding errors?

I have come up with a function that is supposed to take an array of Promises and only return the resolved ones while ignoring any errors. It's similar to Promise.all but without considering errors. The challenge is implementing this function correctly ...

in JavaScript arrays, the identifier follows the numeric value right away

Can anyone assist me with assigning a PHP array of image filenames to a JavaScript array? I have made some progress, here's my code: <script src="jq.js"></script> <?php $dir = 'images'; $images = scandir($dir); $true_images ...

Displaying a Dynamic Loading Animation While Making an AJAX Call with jQuery

When a user clicks on the active status button, it should switch to inactive with a red color, and vice versa. Currently, I can update my status in the backend, but I have to refresh the page to see the changes every time! My requirement is that during t ...

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

Activate the b-form-file function by selecting the b-button

Working with BootstrapVue, I am trying to trigger my b-form-file after clicking on a b-button for style reasons. Additionally, I want the b-form-file to be hidden so it is not visible. I attempted the following approach, but it did not work for me: <b- ...

Create a specific part of a webpage that can be scrolled through

In a unique way, I have designed a page where the only way to navigate is by simply clicking. To achieve this, I have implemented the following custom CSS: body{ overflow:hidden; } However, I have encountered a problem where I am unable to scroll to ...

Utilizing Electron and jQuery to incorporate a loading animated GIF into a newly opened window, where the animation pauses

I am working on an electron project that involves opening a new window with an index.html file. In this newly opened window, I have included an animated.gif in the body section. <!doctype html> <html lang="en> <head> <meta charset ...

What is the most efficient way to loop through a tree structure of interconnected objects and convert them into an array?

A database stores family members on a family tree. A function is designed to query all relatives of a user and compile their contact information and metadata into a list of unique entries, regardless of order. The issue arises when the function only retri ...

Numerous occurrences of directives and their accompanying events

Having a directive that I frequently use on a page has presented me with a challenge. It triggers an event when the state changes, which is then handled by the controller. The issue arises when the event is fired twice, and although I understand why this ...

The toggle function for the hamburger icon is currently malfunctioning

I am facing an issue with the hamburger icon on my website. The toggle functionality associated with it is not working properly. Even though I have a class named change-1 that should be toggled upon clicking the icon, it is not happening. There are no erro ...

Attempt to retrieve node information using the useStaticQuery method in Gatsby

I am facing an issue where I am trying to retrieve information from GraphQL Gatsby using useStaticQuery, but the data returned is showing as undefined. I am confused as to why this is happening because when I check my http://localhost:8000/___graphql endpo ...

Can a C function be designed to handle both double and long double arguments simultaneously?

In the file mag.c, there is a function called mag that calculates the magnitude of an array. #include <math.h> #include "mag.h" long double mag(long double arr[], int len){ long double magnitude=0; for(int i=0;i<len;i++) ...

What steps are needed to implement Javascript functionality for a Carousel with Bootstrap 4?

Hello, I'm having some trouble with a carousel for a restaurant's page. I followed a tutorial to code it using Bootstrap, but the carousel isn't moving as expected. I suspect there might be an issue with the JavaScript, even though I've ...

How can you identify when an input value has been modified in Angular?

For my current project, I am developing a directive to be used with a text input field in order to format currency input. This directive has two HostListeners - one for when the input loses focus and one for when it gains focus. When the blur event occurs, ...

The textures in three.js material do not interact with lighting sources

I am curious about whether a textured geometry can be successfully lit in three.js. In my current scene, I have noticed that all materials receive lighting effectively when using spotLight and directionalLight, except for those that have a texture applied ...

jQuery failing to execute

Can someone help me figure out why my alert isn't working when a button is clicked using jQuery? I'm not sure if it's a syntax error or something else. <!DOCTYPE html> <html> <head> <title>BETA BLOCKER NET</title& ...

Can I add the object to the DOM and hold off on executing any events until the next

Just came across this intriguing interview question (shown below). Could someone please provide an explanation of the question and then offer a solution? Develop a function that takes an object and adds it to the DOM, ensuring that events are stored unt ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

Deleting identical string objects from two arrays or lists in Java

My first question here is regarding Java programming. I want to implement a specific logic: I have two string Arrays (or Lists of strings). One array named asu includes elements M1, M2, M3 ... The other array called rzs consists of elements M1, M2, M3 ...