Trouble with arithmetic operators in AngularJS - javascript

I have following code:
$scope.showTotal = function() {
$scope.pT = [];
var iT = 0;
for (var i = 0; i < $scope.od.length; i++) {
console.log($scope.od[i]['bpr']);
iT += $scope.od[i]['bpr'];
// also tried this -> iT = iT + $scope.od[i]['bpr']
}
$scope.pT.push({iTotal: iT});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
But I don't know why it's not working.
If the bpr is for example 50 and 43.1034, then it logs the output in console something like this, iTotal:"050.000043.1034"
I am new to JavaScript and I started it directly with AngularJS.
So please help me with arithmetic operators in JS.
Thank You.

$scope.showTotal = function() {
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i < $scope.order.length; i++) {
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
// parseFloat will convert string to number and add the number instead of concatenating the strings
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}

You are incrementing i inside the loop .Remove the duplicate i and I suspect that your $scope.order[i]['baseprice'] is not an integer. So convert it to an integer using parseFloat
$scope.showTotal = function(){
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i<$scope.order.length; i++){
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
//also tried this -> itemtotal = itemtotal + $scope.order[i]['baseprice']
//i++; No need to increment here
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}

Related

Finding the sum of a "counter" variable loop that ran ten times then was pushed into the "numbers" array. Each way I tried resulted with a list

I'm asking for help to find the sum of an array with elements that were pushed from a counter variable that had previously looped 10 times. I'm new to Javascript and was practicing for an assessment, and I've tried several different ways to do it and have only resulted with just a list of the elements within the numbers array.
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i ++) {
counter = [i + 73];
numbers.push(counter);
}
console.log(numbers);
function sum(arr) {
var s = 0;
for(var i = 0; i < arr.length; i++) {
s = s += arr[i];
}
return s;
}
console.log(sum([numbers]));
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var numbers = getArraySum([numbers]);
console.log(numbers);
you should push only the value of counter without the brackets and then make a reduce to have the sum of each number in the array
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i++) {
counter = i + 73;
numbers.push(counter);
}
console.log(numbers.reduce((a,b) => a+b));
You had a couple of typos in the code:
Typos
You were wrapping the sum in square brackets:
counter = [i + 73];
You should just remove the brackets like:
counter = i + 73;
2. You were wrapping a value that is already an array in square brackets while passing it as an argument to a function:
sum( [numbers] )
// ...
getArraySum( [numbers] );
You should remove the brackets, like this:
sum( numbers );
// ...
getArraySum( numbers );
Fix
I updated the code that you shared to fix the above-mentioned things:
var numbers = [];
// Loop 10 times and push each number to the numbers array
for (var i = 1; i <= 10; i ++) {
var sumNumbers = i + 73;
numbers.push(sumNumbers);
}
console.log(numbers);
function sum(arr) {
var total = 0;
for(var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// Call the function by passing it the variable numbers, holding an array
var result1 = sum(numbers);
console.log( result1 );
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var result2 = getArraySum(numbers);
console.log(result2);

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});

Average of Numbers in Javascript/Angularjs

I have a json response where have to calculate the average of "throughput_kbps" where protocol name is "TCP" for each result array.
I using Javascript/Angularjs for this
Please refer This json
Thanx in advance
You could do something like this:
var len1 = obj['flows'].length;
for (var i=0; i<len1; i++)
{
var tmp = obj.['flows'][i];
var len2 = tmp.['results'].length;
var mean = 0;
for (var j=0; j<len2; ++j)
{
var tmpResult = tmp.['results'][j];
if (tmpResult['protocol'] === 'TCP')
mean += tmpResult['throughput_kbps'];
}
console.log(mean);
}
Try this
var sum = 0;
var count = 0;
data.flows.map(function(d){
return d.results.filter(function(res){
if(res.protocol == 'TCP'){
sum += res.throughput_kbps;
count++;
return sum;
}
})
});
var avg = sum/count;
Pass your JSON as an argument to this function. This'll return you the average throughput you ask for.
function calculateThroughput(json){
var flowsObj = json.flows;
var throughputSum = 0;
var noOfSamples = 0;
for(noOfFlows in flowsObj){
var resultObj = flowsObj[noOfFlows].results;
for(noOfResults in resultObj){
if(resultObj[noOfResults].protocol == "TCP"){
throughputSum += resultObj[noOfResults].throughput_kbps;
noOfSamples++;
}
}
}
return (throughputSum/noOfSamples);
};
Hope this helps.

What am I doing wrong with this array?

Okay, trying to put together a numeric array and arrange it in ascending order. The more I look, the more I confuse myself. The alerts come up as "undefined." What am I overlooking?
var random = new Array();
function main() {
generate();
original();
ascending(random);
}
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = document.write(Math.floor(Math.random() * 100) + ", ");
}
}
function original() {
var storage = "";
for (var i = 0; i < 25; i++) {
storage += random[i] + ", ";
}
alert(storage);
}
function ascending(random) {
var tempArray = random;
var storage = "";
random.sort(function (a, b) {
return a - b
});
for (i = 0; i < 25; i++) {
storage += tempArray[i] + ", ";
}
alert("ASCENDING- " + storage);
}
No need for document.write (not sure what were you trying to achieve with it), this is enough:
random[i] = Math.floor(Math.random() * 100);
Afterwards, if you need to convert it to a string for output, just join it:
random.join(",");
Here is your generate function:
var random = [];
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = Math.floor(Math.random() * 100);
}
}
generate();
var str = random.join(', ');
document.write(str);
Note: try to avoid using document.write whenever you can.
Take out your document.write() call in generate(), that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.

Why won't my inputs value sum?

Im trying to do a sum of values i get from id but it keeps appending second value to first instead of doing sum as it should.
Example 23+25=2325
Heres my code:
This is the code im using to sum.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
Try this:
var one = parseInt(document.getElementById("veb_blocos-"+i).value, 10);
var two = parseInt(document.getElementById("veb_pellet-"+i).value, 10);
Because the value of an input is a string. Cast it to int.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = parseInt(one,10)+parseInt(two,10);
document.getElementById("total1-"+i).value = sum1;
};
});
Here is the safest possible solution (presuming the requested DOM nodes are present):
$('input').blur(function () {
var i = 0,
one = 0,
two = 0;
for (i = 1; i <= value; i += 1) {
one = Number(document.getElementById("veb_blocos-" + i).value);
two = Number(document.getElementById("veb_pellet-" + i).value);
if (isNaN(one)) {
one = 0;
}
if (isNaN(two)) {
two = 0;
}
document.getElementById("total1-" + i).value = one + two;
};
});
Try:
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseInt(document.getElementById("veb_blocos-"+i).value);
var two = parseInt(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
It's because your values are string datatypes instead of a number type. You'll need to parse them first.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseFloat(document.getElementById("veb_blocos-"+i).value);
var two = parseFloat(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});

Categories