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/

6
  • 1
    Use parseInt(), currently it concatenates as string. Commented Jun 25, 2016 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. Commented Jun 25, 2016 at 19:12
  • No, it would make it clearer to call it an "array". Commented Jun 25, 2016 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. Commented Jun 25, 2016 at 19:15
  • 1
    See stackoverflow.com/questions/14496531/…. Commented Jun 25, 2016 at 19:30

1 Answer 1

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);

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

3 Comments

I would like to thank you for posting this answer and showing me how to rectify the problem of concatenating the ID properties :)
@TheCodesee, I'm glad it helped mate! Happy Coding
Which answer is better out of the two you posted, performance-wise?

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.