Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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

share|improve this answer

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);
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.