How do I collect and sum up these values by Class Name - javascript

I'm trying to add collect all the odds ,loop through the results and add them to array totalArr.
in the second step I tried to sum up the values in the totalArr but its not working. alert(sum)
is returning 03.32.51.82.2
<p class="slip-odds">3.3</p>
<p class="slip-odds">2.5</p>
<p class="slip-odds">1.8</p>
<p class="slip-odds">2.2</p>```
<script type="text/javascript">
let getSlipOdds = document.getElementsByClassName('slip-odds');
let totalArr = [];
for (let i = 0; i < getSlipOdds.length; i++) {
var slipOdd = getSlipOdds[i].innerHTML;
totalArr.push(slipOdd);
}
let sum = 0;
for (let i = 0; i < totalArr.length; i++) {
sum += totalArr[i];
}
alert(sum);
</script>

Convert to number before pushing to the array like this
totalArr.push(Number(slipOdd));

You should convert totalArr[i] to a number before adding.

it's because javascript thinks it's a string, not a number. you can easily multiply your array elements with 1 and it will convert it to a number
sum += totalArr[i] * 1;

Related

For loop returning completely wrong value using power function

As you can see int he code below I separate the n variable and convert back to an integer array. When I put these numbers into my for loop they come out in the billions. Any help would be greatly appreciated.
var n = [86]
var p = [1]
n = n.toString().split("").map(function(value) {
return(parseInt(value))
})
var total = 0;
for(i=0;i<n.length;i++) {
total += (Math.pow(n[i],(p+i))
}
console.log(total)
You need the conversion from strings to numbers and you are adding an array to numbers.
You cannot sum an array to an integer [1]+0, it doesn't result in a number. It will do a concatenation.
var n = [86]
var p = [1]
n = n.toString().split("").map(val => Number(val))
var total = 0;
for (i = 0; i < n.length; i++) {
total += Math.pow(n[i], (p[0] + i))
}
console.log(total);
p is an array not an individual number, in your for loop, when it is running (p+i), that value ends up being 10 and 11. So your first loop is running Math.pow(8,10) and the second time it runs it is running Math.pow(6,11), which, will result in a number in the billions

Get text from each element with certain class and then add up

I'm trying to do some calculations using javascript. I'm basically getting the text of each element with a certain class, convert that to a number and then add those numbers up.
This is what I've got so far:
<p class="item-size">1000</p>
<p class="item-size">2000</p>
JS:
$(document).ready(function(){
var elements = document.getElementsByClassName("item-size");
var size = ''
for (var i=0; i<elements.length; i++) {
size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""));
}
console.log(size);
});
This returns 10002000 in the console. However, I need to get each of those values and then add them up instead of displaying them as one number. So the result should be 3000.
I've tried this:
var myTotal = 0;
for(var i = 0, len = size.length; i < len; i++) {
myTotal += size[i][1];
console.log(myTotal);
}
However, this returns NaN. Any ideas how to do this?
You need a number as target variable.
$(document).ready(function(){
var elements = document.getElementsByClassName("item-size");
var size = 0; // <-- zero instead of an empty string
for (var i=0; i<elements.length; i++) {
size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""), 10); // take base
}
console.log(size);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
var size = 0, when you add string with integer it will return string and calculated as string. int + str = str
Here's ES5 version:
const elements = document.getElementsByClassName("item-size");
const size = Object.keys(elements)
.reduce((acc, curr) =>
acc + parseInt(elements[curr].innerText.replace(/[^0-9.]/g, "")), 0)
console.log(size);
https://jsfiddle.net/becg3vqu/3/
Loop through all the children of an element and for each one increment a number by the textcontent of the element with a unary operator.
function getSumOfClass(className, root) {
if (!(root instanceof HTMLElement)) root = document.body;
return [].reduce.call(root.querySelectorAll("." + className),
(result, dom) => result + (+dom.textContent || 0), 0);
}
console.log(getSumOfClass("item-size"));
<p class="item-not-size">500</p>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
Adding a + or a - infront of a parameter or literal will convert it to a number. If it can't be converted to a number, the result will be NaN so you can just add an || operator to return a 0 in that case (so that the non arithmetic value will be ignored).
Using javascript vanilla
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
<script>
//getting the texts that contain numbers
let items = document.getElementsByClassName("item-size");
let sum = 0;
//Now for each element in the arrays
for (let i = 0; i < items.length; i++) {
sum = sum + parseInt(items[i].innerText);
}
console.log(sum);
</script>
</body>
</html>
Since size is initially an empty string the addition wont work as you expected. Initialize var size to 0.

Javascript calculating in for loops

I have a <p id="rabbits">1 2 9 4</p>' And i'm trying to calculate all the 1,2,9,4
However, I'm stuck at this part:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
for (i in rabbits_array) {
console.log(i) // prints 1,2,9,4
}
How do add all of these numbers together (which is 16 if you count manually) in javascript?
Can map array to number and use reduce
var rabbits = $('#rabbits').text()
var total = rabbits.split(" ").map(Number).reduce((a,c) => a + c)
console.log(total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="rabbits">1 2 9 4</p>
There are a variety of ways to do this.
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
var total = 0;
rabbits_array.forEach(function(element) {
total += element * 1;
});
console.log(total);
You could use a standard for loop:
for (var i = 0; i < rabbits_array.length;i++) {
total += rabbits_array[i] * 1;
}
You could replace the "multiply by 1" (which would have to validate beforehand that it's actually a number and not a letter), with parseInt or parseFloat. Using these methods can do some of this validation for you, but may also give you odd results.
total += parseFloat(rabbits_array[i]);
https://www.w3schools.com/jsref/jsref_parseint.asp
There are other ways to do this as well, but these are just a few examples to get you going. I'd suggest Googling "javascript loops" to read more about this kind of thing.
Try this:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(" ");
var total = 0;
for (var i = 0; i < rabbits_array.length; i++) {
total = total + parseInt(rabbits_array[i]);
}
console.log(total)
You need to convert the string version of the number (from your split function) to an actual number before adding them together

Add multiple numbers to Array

I have two arrays. They look like this:
array price = 14.60, 39.00
and
array quantity = 10, 5
(quantity is the quantity of items the user want to buy - 10 items from productA and 5 of productB)
Now I want loop through the variables to multiply the price with the quantity.
Like :
14,60 * 10
and
39,00 * 5
and add the two results to the endPrice variable.
I get the quantity array like this:
$('.quantity').change(function () {
quantitys = $('input[type=number]').map(function () {
return $(this).val();
}).get();
});
and the different prices like this:
var prices = $('.priceCell').map(function () {
return parseFloat($(this).html().trim());
}).get();
And that's what I tried:
var endPrice = 0;
for (var q = 0; q < quantitys.length; q++) {
for (var p = 0; p < prices.length; p++) {
endPrice = quantitys[q] * prices[p];
}
}
alert(endPrice);
Well, that haven't worked for me so well. Can someone help me there? Doesn't matter if the solution is pure JavaScript or jQuery.
You are using two loops while you should only use one. Also, add to endPrice by using +=:
var endPrice = 0;
for (var q = 0; q < quantitys.length; q++) {
endPrice += parseFloat(quantitys[q]) * parseFloat(prices[q]);
}
alert(endPrice);
1st problem
You were using nested loops thus every quantity would be multiplied by every prices. You only need one loop.
2nd problem
You were using endPrice = .... This will override the endPrice every time you go through this line. You need to use += that will add to the current enbPrice
var prices = [14.60, 39.00];
var quantities = [10,5];
var endPrice = 0;
for(let i=0, l=prices.length;i<l;i++){
endPrice += prices[i] * quantities[i];
}
console.log(endPrice);
EDIT
OP need to have separated totals. (See #David Thomas's answer)
You can use Array.prototype.map()
var prices = [14.60, 39.00];
var quantities = [10, 5];
var totals = prices.map((p, index) => p * quantities[index]);
console.log(totals);
You can't use the double loop for this. This multiplies every price with every quantity. What you want to do is this:
var endPrice = 0;
for (var i = 0; i < quantitys.length; i++) {
endPrice += quantitys[i] * prices[i];
}
To multiply every price in one Array by the number held at the same index in a second Array I'd recommend:
var price = [14.60, 39.00],
quantity = [10, 5],
// here we iterate over the price Array, using
// Array.prototype.map() in order to return a
// new Array:
totals = price.map(
// p: the current array-element of
// the Array of prices,
// index: the index of the current
// array-element of the Array.
// using an Arrow function to
// multiply the price ('p') by
// the value held in the quantity
// Array at the same index:
(p,index) => p * quantity[index]
);
// logging the created 'totals' Array to the console:
console.log(totals); // [146,195]
// logging the created Array, after joining its
// elements together to form a String with values
// separated with a ',' character:
console.log(totals.join(',')); // "146,195"
Close, you're missing += instead of =
endPrice += quantitys[q] * prices[p];
Dependent on your values, you may also want to parse them, so:
endPrice += (parseInt(quantitys[q]) * prices[p]) // you're already parsing prices;
Edit with more information in comments:
Because of the way your code is, they prices are on the same row as the quantities, so they'll be the same. So, the new code will be...
for (var q = 0; q < quantitys.length; q++) {
endPrice += parseInt(quantitys[q]) * prices[q];
}
const prices = [14.60, 39.00];
const qty = [10, 5];
const endPrice = prices.reduce((total, price, i) => total + price * qty[i], 0);
console.log(endPrice);

Summing array on Javascript

Hi I am trying to sum an array on Javascript with the following codes.
var data[]:
var total=0;
data.push[x]; // x is numbers which are produced dynamically.
for(var i=0, n=data.length; i < n; i++)
{
total=total+data[i];
}
alert(total)
for example if x values are are respectively 5,11,16,7. It shows the total value as 511167 not sum the values 5+11+16+7=39
Do you have any idea why it results like that?
Thanks.
Use parseInt() function javascript
total=parseInt(total)+parseInt(data[i]);
Try with parseInt:
total=total+parseInt(data[i]);
Simply whip a unary + before data[i] to convert the string values to numeric values:
total = total + (+data[i]);
Even better, use += instead of total=total+...:
total += +data[i];
JSFiddle demo.
Try this one:
var total = 0;
for (var i = 0; i < someArray.length; i++) {
total += someArray[i] << 0;
}
Use parseInt() javascript function....
total = total + parseInt(data[i]);
This looks the 'x' which you mention come dynamically has a string type. Just check the "typeof x".

Categories