views:

68

answers:

2

I'm looping through 3 arrays, finding 'actionTimings' in each array and adding up the actionTimings values (values are all numbers). How would I assign the 3 values I obtain to a new array? Here's what I have so far...

$.each(dinnerComponents, function(intIndex, component) {
 totalCookTime = 0;
 for ( var i = 0; i < component.actionTimings.length; i++ ) {
  totalCookTime += component.actionTimings[i];
 }
});

I tried this:

totalCookTime = new Array(totalCookTime);

But this array contains 3 sets of an amount of commas (,). Seems like the number of commas = totalCookTime-1. Something to do with values being comma separated? My knowledge of arrays is a little limited I'm afraid.

Thanks for any help.

+2  A: 

You can use the Array push method:

var grandTotals = [];  // will contain the sub-totals for each 'dinerComponent'
$.each(dinnerComponents, function(intIndex, component) {
  var totalCookTime = 0;
  for ( var i = 0; i < component.actionTimings.length; i++ ) {
    totalCookTime += +component.actionTimings[i]; // unary plus to ensure Number
  }
  grandTotals.push(totalCookTime);
});
CMS
A: 

Your problem is essentially that new Array(n) makes an array with n "slots".

In any case, the best thing to do is to use jQuery's "map" method, which converts one array to another array:

var totalCookTime = $(dinnerComponents).map(function (component) {
    var cookTime = 0;
    $(component.actionTimings).each(function (index,timing) {
        cookTime += timing;
    })
    return cookTime;
}).get();

(The final .get() returns an actual array rather than a special jQuery object that behaves like an array.)

Rich