The Codesee The Codesee - 4 months ago 27
Javascript Question

JavaScript Total Returns NaN

I am trying to sum an array of objects using JavaScript, but instead of displaying the expected outcome of 86 it displays

NaN
.

Note: I am not able to edit the array of objects!



var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];

var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
sum += +id[i].ID;
}

document.getElementById('here').innerHTML = "<b>Total:</b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});

<div id="here"></div>





JsFiddle: https://jsfiddle.net/ru266x7m/

Please be aware that this is not a duplicate of Object returning NaN when sum values as I already have the line of code
var sum = 0;

Answer

You could insert a check if the value isFinite.

if (isFinite(id[i].ID)) {
    sum += +id[i].ID;
}

var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];

var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
    if (isFinite(id[i].ID)) {
        sum += +id[i].ID;
    }
}

document.getElementById('here').innerHTML = "<b>Total: </b>" + sum;
objects.forEach(function(key) {
    var a = document.createElement("p");
    a.innerHTML = key.ID;
    document.getElementById('here').appendChild(a);
});
<div id="here"></div>

Comments