0

I need to push the height of each page into an array. However the/my problem is, that I need to push not the values themselves, but a running total of the values.

Here's what I've done so far:

var heights = [0];
$('.page').each(function(i) {
    heights.push($(this).height());
});

The result looks like this: [0, 2000, 1000, 3000, 1500], which is the heights of the pages, but I need something like this: [0, 2000, 3000, 6000, 7500], which is the running total of the page heights added.

3
  • do you mean [2000, 3000, 6000, 7500]? Commented Dec 28, 2012 at 22:38
  • so you want it sorted? just use .sort(); after inserting. Commented Dec 28, 2012 at 22:41
  • @JosephMarikle Whoops, yes! :P Commented Dec 28, 2012 at 22:41

3 Answers 3

3
var heights = [0];
$('.page').each(function(i) {
    heights.push(
        $(this).height() + (heights[i] || 0)
    );
});

EDIT
Edited version now incorporates the leading 0 array member as requested by the questioner.

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

Comments

2

You can do it in a single loop:

var heights = [];
var total   = 0;
$('.page').each(function(i) {
    total += $(this).height();
    heights.push(total);
});

Or... if you want it to be super clean:

var heights = [];
var total   = 0;
$('.page').each((function(){
  var total = 0;
  return function(i) {
    total += $(this).height();
    heights.push(total);
  };
}()));

The second version avoids polluting any scopes with the total variable.

1 Comment

The leading 0 doesn't really change much of the answer.
2

Add this after the code you have:

var total = 0;
for (i=1 ; i < heights.length ; ++i) {
    total += heights[i];
    heights[i] = total;
}

1 Comment

@yckart There. Fixed that.

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.