0

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/

The Codesee
  • 3,714
  • 5
  • 38
  • 78
  • 1
    Use `parseInt()`, currently it concatenates as string. – Shaunak D Jun 25 '16 at 19:09
  • What is a "JSON array"? `ID` is not an "element", it's a "property". "putting each element next to each other" is called concatenation. That's what `+` does with strings. –  Jun 25 '16 at 19:12
  • No, it would make it clearer to call it an "array". –  Jun 25 '16 at 19:13
  • I'm not the downvoter, but the behavior of `+` with strings vs. numbers is well-documented and covered in many questions here on SO, potentially making this question "not useful". For example, see the [MDN page](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators). –  Jun 25 '16 at 19:15
  • @torazaburo I see. I don't see how this question is "not useful" though as it's a genuine mistake and rather than downvoting for a mistake, someone should correct the mistake in an answer so I can learn for next time. – The Codesee Jun 25 '16 at 19:17
  • 1
    See http://stackoverflow.com/questions/14496531/adding-two-numbers-using-javascript. –  Jun 25 '16 at 19:30

1 Answers1

1

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);
Rayon
  • 36,219
  • 4
  • 49
  • 76