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
parseInt still return NaN, not 0. Just use:
On the contrary.
parseInt
convertsnull
toNaN
(after having it converted to the string"null"
). You should not useparseInt
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 to0
. However, if you want to be explicit about it, just put thesamples.push(value)
statement inside anif (value != null)
orif (typeof value == "number")
statement.