I am trying to create a program which finds the average of a set of data which someone enters. I have tried using this code:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total + data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
However, when I run it, no matter what I put in, it always prints “0”. Thank you in advance for your help.
The problem is in the line
total + data[i];
This code will be executed at some result will be generated. But then nothing happens to that value. In javascript Numbers are primitive types. Except objects all data types object. You can't mutate them with =(assigning them to a value).
You need to use assignment expression.
total = total + data[i];
Or the short for that will be
total += data[i];
Another problem is that you are not converting the result of prompt() to a Number. Use Unary Plus + to convert string to number.
Below is corrected version of your code.
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
A cleaner and better version can be achieved using do-while and reduce()
var data = [];
var yesno;
do{
var newdata = +prompt("Enter a piece of data (must be a number)");
yesno = confirm("Would you like to add more data?");
data.push(newdata);
}
while (yesno);
var total = data.reduce((ac,a) => ac + a,0);
var average = total / data.length;
document.write(average);
total + data[i] is an "orphaned expression". Use = or +=.
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
Try this:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a
number)");
data.push(newdata);
var yesno = confirm("Would you like to add more
data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i ++;
var average = total / data.length;
document.write(average);
}
}
Related
This works fine if I sum numbers in JavaScript in an Array. But when I ask their input from User then they are printed as if the numbers are in string. Kindly help me in finding the flaw in my code.
var tArr = [];
for(var f = 1;f<=4;f++)
{
// tArr.push(f);
var z = prompt("Enter numbers for Sum");
tArr.push(z);
}
var r = parseInt(tArr);
alert(tArr);
var summ = 0;
for(var w = 0; w< tArr.length; w++)
{
summ += tArr[w];
}
console.log(summ);
To convert all values to number just do +tArr[w] then sum it. The +tArr[w] will coerce each value into a number instead of a string and hence will sum it instead of concatenating it.
var tArr = [];
for(var f = 1;f<=4;f++)
{
// tArr.push(f);
var z = prompt("Enter numbers for Sum");
tArr.push(z);
}
//var r = parseInt(tArr); This line is not doing anything.
alert(tArr);
var summ = 0;
for(var w = 0; w< tArr.length; w++)
{
summ += +tArr[w];
}
console.log(summ);
var sum=0;
var len=(Number(prompt("Enter len of array")));
var ar=new Array();
for(var i=0;i<len;i++){
ar.push(Number(prompt("Enter array elements:"+ar[i])));
}
for(var i=0;i<len;i++){
sum+=ar[i];
}
document.write(sum+" ");
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.
I want to display duplicates found from the sheet in a Browser.Msg box and send the duplicate strings via email.
Additionally extra column could be written to that row where status "DUPLICATE - YES" would be written. However just to get it via email / in a popup would be enough.
I have tried logging the data. I have tried setting variables.
function checkDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("DATA!F2:F"); // Set Any Range
// "A:A" is for Column A
// And if you want to check duplicates for whole sheet then try this:
// var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var numRows = data.length;
var numColumns = data[0].length;
var dupes = false;
var okdupes0 = 0;
var nodupes0 = 0;
var totbookings0 = 0;
var formats = [];
var values = [];
for (var i = 0; i < numRows; i++) {
formats[i] = [];
for (var j = 0; j < numColumns; j++) {
formats[i][j] = 'WHITE';
if (data[i][j] != '') {
values.push([data[i][j], i, j]);
}
}
}
var numValues = values.length;
for (var k = 0 ; k < numValues - 1; k++) {
if (formats[values[k][1]][values[k][2]] == 'WHITE') {
for (var l = k + 1; l < numValues; l++) {
if (values[k][0] == values[l][0]) {
formats[values[k][1]][values[k][2]] = 'RED';
formats[values[l][1]][values[l][2]] = 'RED';
var dupes = true;
}
}
var okdupes = okdupes0++;
}
var totbookings = totbookings0++;
}
if (dupes) {
// var okdupes = okdupes -1;
var nodupes = totbookings - okdupes;
var emailAddress = "myemail#gmail.com"; // First column
var message = + nodupes + " Duplicate voucher(s) has been found from the system. Duplicate vouchers has been marked with red color."; // Second column
var subject = "System: " + nodupes + " Duplicate Voucher(s) Found!";
MailApp.sendEmail(emailAddress, subject, message);
Browser.msgBox('Warning!', ''+ nodupes +' Possible duplicate voucher(s) has been found and colored red! Please contact the rep who has made the sale. '+ totbookings +' bookings has been scanned through for duplicates.', Browser.Buttons.OK);
} else {
Browser.msgBox('All good!', 'No duplicate vouchers found.', Browser.Buttons.OK);
}
dataRange.setBackgroundColors(formats);
}
You could convert the array of values to a string, then use match to count occurrences.
This code works to find duplicates, even from a two dimensional array. It doesn't determine what cell the duplicate came from. The values of all the duplicates are put into an array.
function findDups() {
var testArray = [['one','two','three'],['three','four','five']];
var allDataAsString = testArray.toString();
Logger.log('allDataAsString: ' + allDataAsString);
//Create one Dimensional array of all values
var allDataInArray = allDataAsString.split(",");
var pattern;
var arrayOfDups = [];
for (var i = 0;i<allDataInArray.length;i++) {
var tempStr = allDataInArray[i];
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var regExp = new RegExp(tempStr, "g");
var count = (allDataAsString.match(regExp) || []).length;
Logger.log('count matches: ' + count);
if (count > 1 && arrayOfDups.indexOf(tempStr) === -1) {
arrayOfDups.push(tempStr);
};
};
Logger.log('arrayOfDups: ' + arrayOfDups);
Browser.msgBox('Thest are the duplicate values: ' + arrayOfDups);
//To Do - Send Email
};
The above example code has a hard coded two dimensional array for testing purposes. There are two occurrences of an element with the value of 'three'.
So I have something like this, but it just outputs the link with 1 at the end of it.
var pagelink = "http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=4&SortAggregation=3&SortCurrency=0&PageNumber=";
var num = 1;
var maxnum = 32;
for(var i = num; i <= maxnum; i++){
pagelink + num
}
So the output just returns:
http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=4&SortAggregation=3&SortCurrency=0&PageNumber=1
First - you need to do some js training. Check out eloquentjavascript.net and go to town.
Answer:
var pagelink = "http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=4&SortAggregation=3&SortCurrency=0&PageNumber=";
var num = 1;
var maxnum = 32;
// You need something to put the output in. Here's an array.
var links = [];
for(var i = num; i <= maxnum; i++) {
links.push(pagelink + i);
}
return links;
var pagelink = "http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=4&SortAggregation=3&SortCurrency=0&PageNumber=";
var results = [];
for(var i = 0; i <= **however many links you want**; i++){
results.push(pagelink + (i % 32 + 1));
}
results // or if you want it delimited, results.join('\n') or whatever other delimiter you want
Your results will be stored in results and you can return it (if in a function) or use it for what you need
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;
};
});