Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller:

myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) {
console.log('abcdctrl');
$http.get("http://localhost:8080/api/session")
    .then(function (response) {
        $scope.data = response.data.session;
    });

$scope.getAvg = function () {
    var total = Number("0");
    for (var i = 0; i < $scope.data.length; i++) {
        total += parseInt($scope.data[i].testing);
    }
    return parseInt(total / $scope.data.length);
}
}]);

Here is the JSON data that I am working with:

{
"session": [
    {
        "id": 1,
        "testing": "91,92,93,94,95,96,97",
        "playing": "11,12,13,14,15,16,17",
        "acc_id": 1
    },
    {
        "id": 2,
        "testing": "101,102,103,104,105,106,107",
        "playing": "1,2,3,4,5,6,7",
        "player_id": 2
    },
    {
        "id": 3,
        "testing": "111,112,113,114,115,116,117",
        "playing": "21,22,23,24,25,26,27",
        "acc_id": 3
    }
]
}

I am trying to calculate the average value of each player for testing and playing, as well as the total average value for testing and playing. While I have been able to print the entire JSON successfully, I am encountering difficulties in accessing specific elements within the JSON structure.

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

Give this a shot:

myApp.controller("efghctrl", ['$scope', 'filterByOrder', '$http', function ($scope, filterBy, $http) {
console.log('efghctrl');
$http.get("http://localhost:8080/api/data")
    .then( function responseSuccess(dataReturn) {
        $scope.information = dataReturn.data.session;
    }, function respondError(dataReturn) {
        // executed if there's an error
        // or the server responds with an error status.
 });

$scope.calculateAverage = function () {
    var sum = Number("0");
    for (var k = 0; k < $scope.information.length; k++) {
       var gradesheet = $scope.information[k].testing.split(',');
       for(var l = 0; l < gradesheet.length; l++){
           sum += parseInt(gradesheet[l]);
       }
    }
    return parseInt(sum / $scope.information.length);
}
}]);

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

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

Ways to identify the current version of webpack installed

Currently in the process of utilizing Webpack to transpile and bundle multiple JS files. I am curious about determining the specific version that I am using. In this scenario, assuming that it is globally installed, how can I identify the version without ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Unraveling Nested JSON into Nested Structs with Golang

Consider the code snippet below: type Input struct { Value1 string Value2 string Value3 string Value4 string Nest } type Nest struct { ID string } input := &Input{} decoder := json.NewDecoder(r.Body) if err : ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

Unraveling JSON through DOJO AJAX and REST techniques

I have been attempting to send a request to a REST server using DOJO AJAX, but unfortunately I am receiving a null object as the result in the console: When CLICKED = click clientX=34, clientY=13 JSON loaded from server: null Below is the code snippet I ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typi ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Is there a way to determine the actual time or percentage completion of a file upload using Telerik RadUpload?

Utilizing the Telerik upload file control with manager is a key component of my project: <telerik:RadUpload ID="RadUpload" Runat="server" MaxFileInputsCount="5" /> <telerik:RadProgressManager ID="RadProgressManager" Runat="server" /> For clie ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Preventing undesired form submissions in HTML and JavaScript

My question might be simple, but it's what I have in mind. When working with two buttons in HTML - one for form submission and the other to trigger a JavaScript event - both buttons end up submitting the form. How can I make sure the second button onl ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...

When using NodeJS with expressJS, remember that req.body can only retrieve one variable at a

I'm having trouble with my login and signup pages. The login page is working correctly, but the signup page is only transferring the password for some reason. App.JS: var express = require("express"); var app = express(); var bodyParser = require("bo ...