0

I am getting NaN and Infinity in getting the max value of my JSON Array object.

I am trying to append the properties of a GeoJSOn data from other JSON. Here's the JSFiddle for reference.

The snippet:

$.map(data, function (e) {
    var dev_id = e.dev_id;
    var data = e.data;
    for (var j = 0; j < data.length; j++) {
        var rainVal = parseFloat(data[j].rain_value);
        arr[j] = parseFloat(rainVal);
    }
    var max = Math.max.apply(Math, arr) * 4;
    console.log(dev_id + " " + max)
    for (var k = 0; k < len; k++) {
        jsonObj_device_id = jsonObj.features[k].properties["device_id"];
        if (jsonObj_device_id === dev_id) {
            var nameR = "rain_intensity";
            var rainValue = max;
            jsonObj.features[k].properties[nameR] = rainValue;
        }
    }
});

2 Answers 2

1

There are cases in your code, where in the AJAX response, you are either not getting the Data i.e. e.data or if you get the data you are not getting rain_value. If you do not get e.data first time, you will get Infinity logged on your console because var max = Math.max.apply(Math, []) results in -Infinity. If you do not get rain_value then parseFloat would give you NaN.

Validate the API response before such operations. Something like this.

    var dev_id = e.dev_id;
    var data = e.data;
    var max = 0, r;
    var arr = [];
    if(data) {
        for (var j = 0; j < data.length; j++) {
            r = data[j].rain_value || 0;
            arr[j] = parseFloat(r);
        }
    }
    if(arr.length) {
        max = Math.max.apply(Math, arr) * 4;
    }

    console.log(dev_id + " " + max);
Sign up to request clarification or add additional context in comments.

3 Comments

If that's the case I wanted it to set the max value to 0. Need to set some conditions, but how?
You should give it a try on your own. Have added some sample code.
Figures! It's just that, the data that I'm getting is not consistent. Thanks for the explanation!
0

Here is a working demo

var rainVal = parseFloat(data[j].rain_value);
if (!rainVal) // check 1
    rainVal = 0;
arr[j] = parseFloat(rainVal);
}
var max = 0;
if (arr) // check 2
{
    maxBeforeTested = Math.max.apply(Math, arr) * 4;
    if (isFinite(maxBeforeTested)) //check 3
        max = maxBeforeTested;
    else 
        console.log("Had an infinite value here.");
}
console.log("Cleaned output: " + dev_id + " " + max)

Basically, you needed some checks, I have added comments as "Check".

  1. Any number greater than 1.797693134862315E+308 is infinity. Use isFinite() to check.
  2. NaN means not a number value, you can check that using isNaN() or simply if()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.