1

Im trying to get the total combined value of a set of numbers. Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong. check the jsfiddle too see example

http://jsfiddle.net/Wd78j/

var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
    x.push(parseInt(z[i]));
}
console.log(x);

var total = 0;
$.each(x,function() {
    total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

3 Answers 3

4

When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.

var x = [];

$('.impressions').each( function( ) {
    var z = $(this).text();
    x.push(parseInt(z, 10));
})

Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.

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

1 Comment

+1 - hope you don't mind that I tweaked your parseInt call, though :)
1

text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.

You want to loop through each impressions element, and keep a running sum going. Something like this should work

var sum = 0;
$('.impressions').each(function(){
   sum = sum + (+$(this).text());
});

Updated Fiddle


Or to keep your original structure (don't forget the radix parameter to parseInt):

var z = $('.impressions');
var x = [];
z.each(function(){
    x.push(parseInt($(this).text(), 10));
});
console.log(x);

var total = 0;
$.each(x,function() {
    total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

Updated fiddle

4 Comments

It actually returns the text of the entire collection as one string, according to console.log(z).
@Mathletics - indeed - I saw that when I looked at his fiddle. Silly me for assuming .text would just return the text of the first element, like all the other jQuery functions do... :)
I never saw unary + used that way before. Slick.
@EdP - I learned that way back when around these parts. I love it
0

You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :

var x     = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
    total = 0,
    n     = x.length;

while(n--) total += x[n] || 0;

$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

FIDDLE

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.