javascript storing array values - javascript

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+"]");

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.

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

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

Related

Seeking Help Understanding Difference between For Loop & .forEach

I have two functions that should produce the same result. I would like clarification as to why they do not. I'm not grasping the significant difference that must exist between for-loop and .forEach.
I'd like to though :)
//
//DEMO OBJECT WITH TWO ARRAYS
//
var myArray = {
myList1 : [1,2,3,4],
myList2 : [5,6,7,8]
}
//
//FUNCTION ONE: Produces the sum of myArray.myList1 as expected.
//
var firstWay = function(){
var sum = 0;
for(var i = 0; i < myArray.myList2.length; i++){
sum += myArray.myList2[i];
}
return sum
};
var results2 = firstWay();
console.log(results2);
//FUNCTION TWO PRODUCES NaN
//1.) I don't know why it produced NaN.
//2.) I don't understand why this function wouldn't produce the same result as firstWay.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur.value;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Remove value from sum += cur.value so it's just sum += cur. The value
you need is already contained in cur.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Many answers just stand in the doc and might be found by googling.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
callback
Function to execute on each element. It accepts between one and three arguments:
currentValue
The current element being processed in the array
index Optional
The index currentValue in the array
array Optional.
The array forEach() was called upon "
So cur in your code is the current element of your array of integers. So it's an integer. So it has no value property, it IS the value you're looking for, as pointed out in a comment.
On the second iteration you wrongly put sum += cur.value.
The right way shoud be : sum += cur.

adding whole total using javascript

function total()
{
var tot = 0;
for(var i = 1; i <= 20; i++)
{
var total_id = "total_" + i;
tot = tot + document.getElementById(total_id).value;
}
document.getElementById(total).value = tot;
}
"this code should display total; i have several total_i id to display my total in each row. then i have display that row total to my total named form"
tot = tot + document.getElementById(total_id).value;
Note that the value of an element is a string, so + here is a string concatenation, not addition (for example, 1 + 1 = 11)
If you want to do addition (1 + 1 = 2), use
tot = tot + parseInt(document.getElementById(total_id).value);
you can replace your code line tot = tot + document.getElementById(total_id).value;
with: tot = tot + parseInt(document.getElementById(total_id).value); as the javascript is taking it as a string not a integr value. We can convert it to integer by using parseInt().
Your immediate problem, as mentioned in another answer, is that you're adding strings, specifically the value property on a DOM element which is a string. You'll find any number of questions on SO about that.
If you have the elements in an array, finding the sum just becomes
function add(a, b) { return a + b; }
function sum(array) { return array.reduce(add); }
sum(elements.map(function(elt) { return +elt.value; });
However, you're also using the anti-pattern of using ID's as a poor-man's way of identifying and referring to DOM elements. It's better just to remember the elements themselves as you create and add them (if in fact that's how they're being created). That way, you don't have to spend the rest of live constructing IDs and adding them to elements and then constructing them again to pass to getElementById to find them again. By "remembering the elements themselves as you create them", I mean instead of doing something like this:
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elt.setAttribute('id', 'total_' + i);
parent.appendChild(elt);
}
or the equivalent in jQuery, do something like
var elements = [];
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elements.push(elt);
parent.appendChild(elt);
}
Now you have the array of elements themselves, and you don't have to poking around with getElementById every time you want to access them.

how can I do an addition of all price elements from a json array in javascript

I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.
My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.
function TallyPoints() {
var eles = [];
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
total += document.getElementsByName(inputs[i].name)[0].value;
}
}
alert('Total: ' + total.toString());
};
What I end up with is a value that looks like this:
Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}
Any ideas?
You probably want parseFloat() so your addition works properly (fiddle):
var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
return p + (parseFloat(c.value) || 0);
}, 0);
See also parseInt(), isNaN(), and Array.prototype.reduce()
Try this:
function TallyPoints() {
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
var val = parseFloat(inputs[i].value);
if (!isNaN(val)) {
total += val;
}
}
}
alert('Total: ' + total);
};
parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName, since you already have the element in inputs[i]. There's no need to use total.toString(); concatenating a number to a string converts it automatically.
The if (!isNan(val)) test skips over the inputs that don't contain numbers.
You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

Writing a javascript to find sum of a series using for loop

I am having a problem in writing a javascript for finding the sum of the first 10 natural numbers. I have written the code with a while function and it is working well:
var total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total);
I am now wondering how you can do this using a for loop, if it is possible. Any help?
var total = 0;
for (var i = 1; i <=10; i ++){
total += i;
}
console.log(total);
An alternative for loops in this case is - reduce.
Arrays have reduce method which usage looks like this:
[1,2,3,4].reduce(function(total, number) {
return total + number;
}, 0);
You pass in a function accepting a total and current number from array and return their sum.
Zero at the end is starting value.
Arrays also have forEach method which you can use to iterate through your array like this:
var sum = 0;
[1,2,3,4].forEach(function(number) {
sum += number;
});
PS: reduce in some languages has an alias - fold.
Yet another variant based on lukas.pukenis answer
Array.apply(null,Array(10)) // [undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
.map(function(_, index){
return index+1;
}) // [1,2,3,4,5,6,7,8,9,10]
.reduce(function(total,curr){
return total+curr
}); // 55

Categories

Resources