Reputation: 1
var numbers = [{grades:[100,100,100]}];
var result = 0;
for (var i=0;i<numbers.length;i++){
for (var p in numbers.grades[i]);
result+=p+":"+numbers[i][p];
//console.log(p+":"+numbers[i][p])
console.log(result);
}
this is what i have so far. I know how to get all the numbers in the .grades but i want them all added up in a very simple way.
Upvotes: 0
Views: 349
Reputation:
The list you want to loop through is :
var list = numbers[0].grades;
Then, inside the loop :
result += list[i];
That's it :)
How to browse a javascript array :
var a = ['I', 'need', 'the', 'basics'];
console.log(a[0]); // "I"
console.log(a[3]); // "basics"
console.log(a[a.length - 1]); // "basics"
How to browse a javascript object :
var o = { a: 'I', b: 'need', c: 'the', d: 'basics' };
console.log(o.a); // "I"
console.log(o.d); // "basics"
console.log(o['d']); // "basics"
All together :
var mixed = [{ a: 'foo' }, { b: 'bar' }, { c: ['baz'] }];
console.log(mixed[0].a); // "foo"
console.log(mixed[1].b); // "bar"
console.log(mixed[2].c[0]); // "baz"
To add up all grades :
var grades, i, j;
var sum = 0;
var list = [
{ grades: [1, 2, 3] },
{ grades: [4, 5, 6] }
];
for (i = 0; i < list.length; i++) {
grades = list[i].grades;
for (j = 0; j < grades.length; j++) {
sum += grades[j];
}
}
console.log(sum); // 21
Upvotes: 0
Reputation: 813
You almost had it
var numbers = [{grades:[100,100,100]}];
var result = 0;
for (var i=0;i<numbers.length;i++){
for (var g=0; g<numbers[i].grades.length; g++) {
result = result+numbers[i].grades[g];
console.log(result);
}
}
As discussed, if it does support ES5, you can write it like this:
var numbers = [{grades:[100,100,100]}];
var result = 0;
numbers.forEach( function(val) {
result = result + val.grades.reduce( function (previousValue, currentValue, index, array) {
return previousValue + currentValue;
})
});
just remember that you need to loop through the numbers array, instead of giving it a default value of '0' // numbers[0]grades etc
Upvotes: 1
Reputation: 4881
A more functional/javascript approach would be to use array.reduce()
:
var sum = numbers[0].grades.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
console.log(sum);
Upvotes: 0
Reputation: 77778
The problem you have is numbers.length
is only 1
. You want
numbers[0].grades.length; // 3
This should sum the grades for you
for (var i=0, sum=0; i<numbers[0].grades.length; i++) {
sum += numbers[0].grades[i];
}
sum; // 300
If you have access to Array.prototype.reduce, you could use this
var sum = numbers[0].grades.reduce(function(a, b) { return a + b; }, 0);
sum; // 300
Note .reduce
requires ECMAScript >= 5
and will not work in IE <= 8
Upvotes: 3
Reputation: 28528
or you can try:
for(var j=0; j<numbers.length;j++)
{
for (var i=0, sum=0; i<numbers[j].grades.length; i++) {
sum += numbers[j].grades[i];
}
}
console.log(sum);
Upvotes: 0