Calculating the mean value from a JSON array

I'm having trouble calculating the average from my variable output. I keep getting NaN or zero as a result.

Here is my initial output:

console.log(data)
0: {nodeId: "53", SNR: "[38.2, 38, 37.9, 37.8, 37.6]", timestamp: 
"2019-09-05 00:00:17"}

Next, I extract only the SNR values:

console.log(SNR);
["[38.2, 38, 37.9, 37.8, 37.6]"]

I attempted the code below to calculate the average, but it consistently returns 0 and doesn't recognize the numbers within the square brackets:

      0[38.2, 38, 37.9, 37.8, 37.6]
$(document).ready(function() {
    $.ajax({
        url: "http://localhost:8080/data.php",
        type: "GET",
        success: function(data) {
            console.log(data);
            var SNR = [];
            for (var i in data) {
                SNR.push(data[i].SNR);
            }
            console.log(SNR);
            const numbers = [SNR];
            const sum = numbers.reduce((total, n) => total + n, 0);
            console.log(sum);

        },

        error: function(data) {

        }
    });
});

Input information:

[{"nodeId":"53","SNR":"[38.2, 38, 37.9, 37.8, 37.6]","timestamp":"2019-09-05 00:00:17"},{"nodeId":"53","SNR":"[38.2, 37.9, 38.4, 37.9, 38.3]","timestamp":"2019-09-05 00:15:17"}]

Desired output after parsing SNR values:

0: 37.9
1: 38.1

Answer №1

 $(document).ready(function () {
        var jsonData = {};
        var sensorData = [{ "nodeId": "53", "SNR": "[38.2, 38, 37.9, 37.8, 37.6]", "timestamp": "2019-09-05 00:00:17" }, { "nodeId": "53", "SNR": "[38.2, 37.9, 38.4, 37.9, 38.3]", "timestamp": "2019-09-05 00:15:17"}];

        $.each(sensorData, function (index, element) {
            var sum = 0;
            snrValues = JSON.parse(element.SNR);
            $.each(snrValues, function (subIndex, value) {
                sum += value;
            });
            jsonData[index]={ average: (sum / snrValues.length) };
        });
        console.log(jsonData);
    });

Give this a shot.

Answer №2

Based on the information provided, it seems clear that the issue lies in the fact that the variable SNR is being treated as a JSON-ish string instead of an actual array.

To address this issue with minimal impact on your existing code,

You could try using SNR.push(JSON.parse(data[i].SNR));

Implementing this change should help resolve the problem.

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

PHP Proxy - Sending Files using cURL

I am in the process of developing an application using AngularJS for the frontend and a Laravel-based API for the backend. To maintain security, I pass data through a PHP proxy before reaching the API. When it comes to POST requests, the proxy decodes the ...

How can one stop PHP warnings and errors from disrupting the JSON parser?

I have a PHP script that retrieves a record from a database and returns a JSON object. The script includes error handling to ensure that even if an exception is thrown or other errors occur, it still provides a properly formatted JSON response with an erro ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Seeking further clarification on the topic of `custom Directive` in AngularJS

Implementing a login form in my application, I have chosen to display errors on blur of the input element. Although this approach works, I have encountered several questions regarding a custom directive I created without thorough explanation from the tuto ...

Having issues with utilizing $fetchState in Nuxt 2.12

Recently, I've been exploring the new functionality outlined in the documentation. However, I'm encountering an error that states : Property or method "$fetchState" is not defined on the instance but referenced during render. Despite clearly ...

The ID value did not pick up the number 0 when passed to the next blade after the initial reading

When passing an ID value to another blade file, I encountered an issue where the other blade file did not read the number 0 at the beginning. For example, if I pass the value of 006, when I console log the value in the other blade view, it only shows 6. H ...

Encountering an issue while attempting to assess a Meteor package within a local environment

Hello everyone! I'm a beginner in Meteor programming and currently following the online book discovermeteor.com. I recently came across a chapter that covers the creation of Meteor Packages. Excitedly, I proceeded to create my own package using the ...

Changing the value of a JSON object

My goal is to update a value in a JSON file by removing the last character from a URL. I wrote the following code, but unfortunately, it doesn't seem to be making any changes. I'm a bit lost on what went wrong... def modify_json(file): with ...

The functionality of images and links is compromised when they are assigned as values to properties within a JSON object

My images and links are not working, even after declaring them globally. When I write the src directly into src, everything seems fine but the alert pops up with the same URL and img src. Can anyone help? var combo0; var combo1; var combo2; var combo3; ...

The Response from the HTTPClient POST Request is Rendering Incomprehensible

After successfully sending a response in Postman, I encountered an issue when trying to do the same in C#. Although the response indicates success, the content appears illegible. \u001f\b\0\0\0\0\0\0\0uTs0\ ...

What is the best way to add a div container to a particular section of a webpage?

I have come across many solutions that involve using JQuery, but I am specifically looking for a pure JS method. Currently, I create a div, add content to it using Create Element and innerHTML, and then use appendChild to place it at the bottom of the body ...

`Troubleshooting Issue: Autocomplete feature in Jquery Codeigniter not functioning

Having an issue with autocomplete in my codeigniter project. When I input text into the field, a dropdown appears but no values are shown. It looks like this: Screenshot The error displayed in the console is: Screenshoot Below is the relevant code: Mode ...

Utilizing VueJS to effectively integrate the Google Places API with multiple references

I am currently integrating the Google Places API into my project and have encountered an interesting challenge. I need to implement multiple delivery addresses, requiring me to modify how the Google Places API functions. Below is my existing code snippet: ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

Controlling Javascript events

Currently, I am working on implementing an in-place editor using jQuery. The functionality is such that when you click on the text you wish to edit, it will replace the content with an input field, specifically a select tag. Everything seems to be functio ...

Multiplying arrays with multiple dimensions using the outer product formula

There are d different numpy arrays, each with the shape (2, s, t, ...). To multiply each of them together and produce an output of the shape (2, ..., 2, s, t, ...) with d instances of 2, we can use the following example with d==3: import numpy d = 3 a = ...

What is the best approach to displaying child nodes in JsTree when they are only generated after the parent node is expanded?

Dealing with multiple children nodes under a parent can be tricky. For instance, when trying to open a specific node using $("#jstree").jstree("open_node", $('#node_27'));, you may encounter an issue where the parent node is not initially open, c ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...

The toThrow() function in Jest seems to be malfunctioning

Even though my JS code throws the correct error, it still fails. Here is the relevant Jest code block: describe('operate', () => { test("works with addition", () => { expect(evaluate_expression("3+5")).toEqu ...

import external script in the head using requirejs

Here is my unique HTML structure: <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8"> <title>vente-privee.com</title> <script src="@Url.Content("~/Scripts/Modules/lib/j ...