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

What is the best way to prevent a fetch request from being initiated before the authentication token has been received

After successfully logging in, the data request fetch function needs to send the request with the saved token bearer. However, the data fetch is not waiting for the token and is receiving an Unauthorized access code. This is how my data request fetch func ...

Fetch and showcase JSON information from a CodeIgniter method

Is there a way to retrieve data from a SQL database using ajax (json) with Codeigniter or PHP? I have attempted it, but the result shows up as "undefined." Here is the code snippet: My jQuery code snippet: $('[id^="menuitem_"]').on('click& ...

Combining numerous inputs into an array in a React component

As a beginner in coding, I am eager to learn React by building a project. Currently, I am facing a challenge and seeking guidance. My goal is to store all these values in an array structured as follows: { option: { size: ["Small", "Medium", "Large"] ...

Prevent Dehydration issue while using context values in Next Js

Every time I log in with a user, update a context value, and re-render some components, I keep encountering a Hydration error in Next Js. The issue seems to be specifically with my NavBar component which is rendered using react-bootstrap. The code snippet ...

Header slide animation not functioning properly - toggles up when scrolling down and down when scrolling up jQuery issue

I'm currently experimenting with jQuery to hide the header when scrolling down and make it reappear when scrolling up, but I'm having trouble getting it to work properly. All the content that needs to be animated is within a header tag. $(docum ...

Update the image source every few seconds

I am attempting to show the same image in both gif (animated) and jpeg formats. I am updating the src every few seconds. After checking in the developer tools, it seems that the src has been modified, but the gif does not appear to be animating. setInter ...

Select2 loading screen featuring preloaded value

Trying to populate a select2 box with instrument options on an edit profile page for a musician site. The information is pulled from the database, but I'm struggling to display the existing instrument list in the select2 box upon render - it always ap ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

requiring a page reload for an AJAX-loaded webpage

Encountering an issue with a third-party integration on a website specifically designed for iPads, where multiple pages are loaded using AJAX. Upon visiting the page for the first time, the expected functionality is missing and only appears after refreshi ...

Should I use an array literal or split a string?

Imagine you are in need of a predetermined list of words (the focus here is not on the debate surrounding hard-coding). Would you choose this approach: var items = 'apple banana cherry'.split(' '); Or do you favor this alternative: ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Dynamically fetching data with Node.js using Ajax requests

Despite my efforts to scour Google and Stack Overflow, I have been unable to find a reliable method for posting data to my Node.js server. I've noticed conflicting information on various methods, likely due to changes over time. One particular code ...

Blur Event Triggered in Primefaces Editor

My current setup involves using JSF Mojarra 2.2.8 with PrimeFaces 5.1, where I utilize a PrimeFaces editor for text input. I am looking to automatically upload the entered text via ajax. However, the editor only supports an onchange event. I'm seekin ...

The JSON java.sql.SQLException occurs when attempting to execute a Positioned Update that is not

In my attempts to utilize JSON in Java Web development, I encountered an issue when trying to transform a List into a JSONArray using the JSONArray.fromObject() method. The exception thrown is as follows: java.sql.SQLException: Positioned Update not suppo ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...

When attempting to display the details of each restaurant on my detail page, I encountered the error "Cannot read property 'name_restaurant' of undefined."

I have set up dynamic routing for a ProductDetail page, where each restaurant has its own details that should be displayed. The routing is functional, but I am facing difficulty in retrieving data from Firestore using the restaurant's ID. PS: Althoug ...

Creating a flowchart of a finite state machine within a browser-based software platform

If you're curious about the core logic behind my application, check out this link for a great explanation: Code Golf: Finite-state machine! I plan to implement this logic to create finite state machines on my web app using a library. I've been ...

Tips for resolving the error "Encountered duplicate registration of views named RNGestureHandlerButton" in ReactNative

Seeking guidance on implementing a Swipe-to-Delete feature in my App, I manually installed the react-native-gesture-handler. This action triggered an error message which persists even after attempting to uninstall the gesture handler. Any suggestions or so ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...