1

Can't get array reduce to work:

var labels  = ["MetricLinuxMemory","memCached","memTotalFree","MetricLinuxCPU","CpuRawSystem","memTotalSwap"];
var columns = [{values:[12,1,2,23,null,2]},{values:[12,null,2]},{values:[12,1,2]},{values:[12,1,2]},{values:[12,1,2]},{values:[12,1,2]}];

var data = {};      //Selected Performance data

// Loop through labels
for (var i = 0; i < labels.length; i++) {   

    var label = labels[i];

    //Search for calculated vlaue (Metric)
    if(label.includes("Metric")){

        //Create property in data object
        data[label] = {};

        var metric  = data[label];
            metric.samples = [];
            metric.sum  = 1;

        //Get appropriate column
        var values = columns[i].values;

        // Loop through values
        for (var ii = 0; ii < values.length; ii++) {    

            //Convert to numeric
            var value = parseInt(values[ii], 10);

            //Push to data
            metric.samples.push(value);
            metric.sum = metric.samples.reduce(function(a, b) { return a + b; }, 0);

        }


    }
}

Desired output would be:

{
    "MetricLinuxMemory": {
        "samples": [
            ...
            23,
            null,
            ...
        ],
        "sum": 40
    },
    ...
}

However i can not seem to get one sum to work. And get null in MetricLinuxMemory instead. Shouldn't parseInt take care of the null input and convert it for example to 0?

2 Answers 2

1

Shouldn't parseInt take care of the null input and convert it for example to 0?

On the contrary. parseInt converts null to NaN (after having it converted to the string "null"). You should not use parseInt on anything else but strings!

If you had just left it out, it would even have worked, since addition of a number with null causes it to be coerced to 0. However, if you want to be explicit about it, just put the samples.push(value) statement inside an if (value != null) or if (typeof value == "number") statement.

Sign up to request clarification or add additional context in comments.

Comments

0

parseInt still return NaN, not 0. Just use:

var value = values[ii] == null? 0 : parseInt(values[ii], 10);

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.