0

I need to sum all of the values of a key "number" from several objects within an array. What would be the correct way to do this? This is what I've tried.

var numarray = [{"number":"10"},{"number":"2"},{"number":"5"},
{"number":"3"},{"number":"21"},{"number":"43"},{"number":"30"}];

function Sum() {
  var sum;

  for (number in numarray[i]){
    alert(sum); //sum would be the result I need to get
  }
}
1
  • Please use the search ([javascript] sum properties) before you ask a new question. There are quite a few similar questions which could help you. Commented Jun 12, 2016 at 4:01

2 Answers 2

3

Use forEach to loop through each of the json object.

Use parseInt to convert the values to integer

var numarray = [
{"number":"10"},
{"number":"2"},
{"number":"5"},
{"number":"3"},
{"number":"21"},
{"number":"43"},
{"number":"30"}];

function Sum(){
var sum=0;

numarray.forEach(function(item){
 sum += parseInt(item.number)
})
document.write('<pre>'+sum+'</pre>')
}
Sum()

DEMO

EDIT

When using parseInt it is better to specify the radix

parseInt(item.number,10)

Using a 10 radix means the number is parsed with a base 10 and thus turns the number into the integer .If parseInt detects a leading zero it will parse the number in octal base

Using Number

Number(item.number)

It will not detect any any octal

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

3 Comments

What would be item in this case? the value of the object?
Specify the radix for parseInt.
Why use parseInt instead of Number?
2

You can use reduce for this:

Here's how you would normally find the sum of elements in an array:

var sum = arr.reduce(function(a,b) {
  return a + b;
});

Since you have an array of objects, you'll need to change this to something like:

var sum = arr.reduce(function(a,b) {
  return parseFloat(a) + parseFloat(b.number);
}, 0);

Notice the 0 I've added added as a parameter? It's the default parameter and required in this case.

Comments

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.