The Codesee The Codesee - 5 months ago 11
Javascript Question

Add up property from array of objects

I am trying to add up the ID property from an array of objects. The result displayed is 01395 - instead, it should be 27 (as that's what 13 + 9 + 5 equals).

I believe the code is concatenating the ID properties rather the desired outcome of adding them.



var collection = [{
"Name": "Charlie",
"ID": "13"
}, {
"Name": "Emma",
"ID": "9"
}, {
"Name": "Bob",
"ID": "5"
}];

total = 0, //set a variable that holds our total
id = collection, //reference the element in the "JSON" aka object literal we want
i = 0;
for (i = 0; i < id.length; i++) { //loop through the array
total += id[i].ID; //Do the math!
}
console.log(total); //display the result





JsFiddle: https://jsfiddle.net/3r8vhfb2/

Answer

Convert it to Number

Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

var collection = [{
  "Name": "Charlie",
  "ID": "13"
}, {
  "Name": "Emma",
  "ID": "9"
}, {
  "Name": "Bob",
  "ID": "5"
}];

var total = 0,
  id = collection;
for (var i = 0; i < id.length; i++) {
  total += +id[i].ID;
  //OR total += Number(id[i].ID);
}
console.log(total);

Or using Array#reduce :

var collection = [{
  "Name": "Charlie",
  "ID": "13"
}, {
  "Name": "Emma",
  "ID": "9"
}, {
  "Name": "Bob",
  "ID": "5"
}];

var total = collection.reduce(function(a, b) {
  return +(a.ID || a) + +(b.ID);
});
console.log(total);

Comments