Putting method with loop doesnt work - javascript

I'm trying to inserting the values of counter into an array called numpay.Unfortunately nothing happens.Where's my mistake?Here's what i tried below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example-1</title>
</head>
<body>
<p id="demo"></p>
<script>
function validateForm() {
var months=(principal+principal*interestrate*0.01)/monthlypayment;
var numpay = new Array(months);
for(var i=0;i<=months-1;i++)
{
numpay.push(i);
text += numpay[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

Fixing existing problems
As others have pointed out, something like this should work:
var months = 12;
var numpay = []; // just as easy
var text = "";
for (var i = 1; i <= months; i++) {
numpay.push(i);
text += numpay[i - 1] + "<br/>";
}
document.getElementById('demo').innerHTML = text;
<p id="demo">(empty)</p>
Enhancing your skills
Although you're combining them in your for-loop, you're doing two separate things here: filling out the months, and creating the text you want to add to the DOM.
There's a lot to be said for one bit of code doing only one thing. You could write a reusable range function which uses more modern JS techniques to give you a numeric integer range between two values. So
const range = (lo, hi) => [...new Array(hi - lo + 1)].map((_, i) => i + lo);
Using that, you can create your months variable by calling this function:
const months = range(1, 12);
Then, with this array, you can use Array.prototype.join to combine the values into the text you would like:
const text = months.join('<br/>')
And that leads to a nicer bit of code:
const range = (lo, hi) => [...new Array(hi - lo + 1)].map((_, i) => i + lo);
const months = range(1, 12);
document.getElementById('demo').innerHTML = months.join('<br/>');
<p id="demo">(empty)</p>
If you need that text variable for something additional, then just assign it as the result of the join, and then assign the innerHTML to it.
Obviously that range function is unnecessary. You could just write const months = [...new Array(12)].map((_, i) => i + 1);. But thinking in terms of such abstractions often lets you write cleaner code.

1.) By creating an array like that (new Array(12)) you are saying to create 12 undefined entries in the array. Then you are pushing to the end of the array.
2.) You also need to initialize text with months var months = 12, text;.
var months = 12, text;
var numpay = new Array(months);
for(var i=1; i<=months; i++){
numpay[i] = i;
text += numpay[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
This will still give you undefined at index 0 but I will leave that for you to work out. But doing numpay[i] = i will overwrite your undefined that was created with the array.

Arrays in JS are zero-based, so if you do .push(i) with i === 1, the value 1 goes into the slot for numpay[0].
And then to access that item, you must use numpay[i-1].
Another thing is that you seem to have forgotten to declare and initialize text before the loop starts. You need to do that, if not then the variable only exists inside the loop body (and loses its value each time the loop body ends).
Demo:
var months = 12;
var numpay = []; // just as easy
var text = "- ";
for (var i = 1; i <= months; i++) {
numpay.push(i);
text += numpay[i - 1] + " - ";
}
console.log(text);

When you instantiate an array with a parameter like this:
var numpay = Array(12);
it results in an array with 12 undefined elements. When you push a new item, it will be placed in the 13th slot.
Instead, just do this:
var text = "";
var months=12;
var numpay = [];
for(var i=1;i<=months;i++)
{
numpay.push(i);
text += numpay[i-1] + "<br>"; //use i-1 here, not i
}
document.getElementById("demo").innerHTML = text;
The result is:
"1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>"

Related

How to split String, convert to Numbers and Sum

I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);

Locating all cell's positions in google sheets

The problem is: I have big spreadsheet (more than 4500 rows) with a lot of data in the first column - for ex. with types of fruits, which are not unique, like this:
APPLE
BANANA
APRICOTS
APPLE
BLACKCURRANT
APPLE
BANANA
APRICOTS
etc.
What I need - locate each BANANA, to be able to put in cell beside some info, for ex. YES. I tried to loop solution from Locating a cell's position in google sheets using a string or an integer but for sure my code is wrong. I already spent a lot of hours to invent something, but still don't understand what I'm missing.
function test(){
var dispatch = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FRUITS");
var find = dispatch.getRange("A:A").getValues();
var name = "BANANA";
var lastRow = dispatch.getLastRow();
var n = 1;
var temp = dispatch.getRange(n, 2).getValue();
var i = 0;
while (temp != ""){
for(var n in find){
if(find[n][0] === name){break}
}
n++;
var n = n + i;
dispatch.getRange(n, 2).setValue("YES");
var temp = dispatch.getRange(n, 2).getValues();
var find = dispatch.getRange(n, 2, lastRow).getValues();
var i = n;
}
}
I will be very grateful for the help.
The code example is below:
function test(){
var dispatch = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FRUITS");
var range = dispatch.getRange(1, 1, dispatch.getLastRow(), 2);
var values = range.getValues();
values.map(function(row) {
if (row[0] == "BANANA")
row[1] = "YES";
});
range.setValues(values);
}
JS array map() method does the most part of work. We convert range values to JS array and back after mapping completes.

How do I use a for-loop to add values to a JS variable? [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I have made a piece of code that generates a random code of 12 characters. I am using Math.random and for-loops to do this. On the page you can write in an input how many codes you want.
What I want to do is save the generated codes in an array, however I can't do this because the for-loop and Math.random creates the code number by number and places them after each other. How can I add the whole 12 digit code to my array (so I can use it later)?
I've tried array.push with no luck. What works is outputting the numbers to DOM object in HTML, like this:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
But that doesn't put the 12 digit code into a variable. I've also tried this:
var codeNumber = "";
codeNumber += mathRandom;
But that ends up in the variable value having only 1 digit.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
I expect the codes created (after some changes) to be added to the array, so that I can later use the codes on the page. Each individual 12-digit code needs to have its own place in the array.
This should work:
var result = [], stringResult;
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
result.push(mathRandom);
}
stringResult = result.join(''); // concatenates all the elements
console.log(stringResult);
The problem with your code is that + sign attempts to determine types of the operands and to choose the right operation, concatenation or addition. When adding stuff to innerHtml it treats the number as string. That is why it worked.
You'll want to refactor things so generating a single code is encapsulated in a single function (generate() here), then use that function's output, like this. (I hope the comments are enlightening enough.)
var numberOfCodes = document.querySelector("#numberOfCodes");
var resultDiv = document.querySelector("#result");
function codeGen() {
var nToGenerate = parseInt(numberOfCodes.value);
for (var a = 0; a < nToGenerate; a++) {
var code = generate(); // generate a code
// you could put the code in an array here!
// for the time being, let's just put it in a new <div>
var el = document.createElement("div");
el.innerHTML = code;
resultDiv.appendChild(el);
}
}
function generate() {
var code = ""; // define a local variable to hold the code
for (i = 0; i < 12; i++) { // loop 12 times...
code += Math.floor(Math.random() * 9); // append the digit...
}
return code; // and return the value of the local variable
}
<input type="number" id="numberOfCodes" value=8>
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
As this answer shows, this should work for you:
function makeRandCode() {
var code = "";
var ints = "1234567890";
for (var i = 0; i < 12; i++) {
code += ints.charAt(Math.floor(Math.random() * ints.length));
}
return code;
}
console.log(makeRandCode());
The problem is that you are adding numbers and what you really want is to concatenate them, the solution is to transform those numbers into String, then save them in the variable where you want to store them. An example:
2 + 2 = 4 and '2'+'2'='22'
Just use .toString() before save it in to the variable.

JS how to Sum/Average?

I have an object and need to sum/average of each dynamic span. Can't seem to convert those to numbers though. Please Help.
Console Log
Code Sample
Expand/Collapse Created : 1/3/2017 ‎<span>(10)‎</span>
Expand/Collapse Created : 1/4/2017 ‎<span>(38)‎</span>
Expand/Collapse Created : 1/5/2017 ‎‎<span>(13)</span>
Expand/Collapse Created : 1/6/2017 ‎‎<span>(35)</span>
Expand/Collapse Created : 1/9/2017 ‎‎<span>(46)</span>
Expand/Collapse Created : 1/10/2017 ‎‎<span>(17)</span>
Expand/Collapse Created : 1/11/2017 ‎‎<span>(27)</span>
var arr = [];
$(".ms-gb span").each(function(index, elem){
arr.push($(this).text());
});
$("#result").text(arr.join("+")); // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
var allNumbers = document.getElementById('result').innerText; // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
allNumbers = allNumbers.replace(/["'()]/g,""); // ‎‎10+‎38+‎13+‎35+‎46+‎17+‎28
var newString = allNumbers.split("+"); // Object - ["‎10", "‎38", "‎13", "‎35", "‎46", "‎17", "‎27"]
well you're pretty close. i'd recommend using the reduce function
var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)
the plus signs in front of a and b might look weird, but its a quick way to coerce a string into a number in javascript
You can strip out non-numeric characters, parse each number, and then perform the addition within the loop.
// variables
var sum = 0;
var average = 0;
var numOfSpan = $('span').length;
// each span loop
$('span').each(function(key, val){
// add the value of the span to the sum var
sum+= parseInt($(this).text().replace(/\D/g,''));
// on the last itteration ...
if(key == (numOfSpan - 1)) {
// calulate average
average = sum / numOfSpan;
// log sum and average
console.log('sum = ' + sum);
console.log('average = ' + average);
}
});
<span>(10)</span>
‎<span>(38)</span>
<span>(13)</span>
<span>(35)</span>
‎<span>(46)</span>
‎‎<span>(17)</span>
<span>(27)</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have to iterate your array and then change every string to number. After that you can add every elements to itself.
var a = 0;
for(var i=0;i<newString.length;i++) {
a += parseInt(newString[i]);}
And then a will be the sum

Sorting and Median with Arrays in Javascript

I have been working on this code, and the goal is to sort out the numbers in the array, and then find the median. My median isn't outputting correctly, and when I try to just see what is in array[0], it never has the right value. I'm not exactly sure where I messed up.
Code:
var array = [];
window.onload = function (){
var answer = '';
var median = 0;
for (var i = 0; i < 8; i++) {
var rand = Math.floor(Math.random() * 101);
array.push(rand);
array.sort(function(a, b){return a-b});
answer = answer + array[i] + " ";
}
median = ((array[3] + array[4]) /2);
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
I would suggest first moving your loops ending. Currently you are sorting every single time you add a new number to the array. This means two things : you are wasting computation power on something you should only do once and when you 'log' your result in the line answer = answer + array[i] + " "; its constantly changing since the order is changing. Your functions logic is correct so by making the change below you should get the result you want.
var array = [];
window.onload = function (){
var answer = '';
var median = 0;
//Loop is simplified to just push a random value
for (var i = 0; i < 8; i++) {
array.push(Math.floor(Math.random() * 101));
}
//Sort is outside of the loop;
array.sort(function(a, b){return a-b});
//Median is outside of the loop
median = ((array[3] + array[4]) /2);
//answer is outside of the loop (if you don't know reduce look at the link below)
answer = array.reduce( function ( answer , value ) {
return answer + ',' + value;
} );
// put into the dom
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
If you need help with this feel free to message me, also checkout the documentation for reduce HERE.
Using purely SO posts, I came up with a solution.
Strategy
Shuffle
At first, the partial expression (Math.floor(Math.random() * 101)) came up with duplicates, that's weaksauce. Fisher-Yates (aka Knuth) Shuffle has an excellent algorithm.
Your var answer and reduce expression is now combined and out of the loop as per #hyphnKnight explained. There's no need to break it down any further because reduce return is everything you need to display a sorted array. I also used unshift instead of push, I read that it's faster to use the front of the array rather than the back, but you can't tell the difference, too small of a function and all.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>35469092</title>
</head>
<output id="result"></output>
<body>
<script>
// 1. Populate an array with the numbers 1 through 100.
var arr = [];
for(var i = 1; i <= 100; i++) {
arr.unshift(i);
}
median(arr);
function median(arr){
var median = 0;
// 2. Shuffle
var ran100 = shuffle(arr);
var ran8 = [];
for(var j = 0; j < 8; j++) {
// Take the first 8 elements of the resulting array.
ran8.unshift(ran100[j]);
}
var answer = ran8.sort(function(a, b){return a-b});
median = ((ran8[3] + ran8[4]) /2);
document.getElementById("result").innerHTML = answer + "<br />" + median;
}
function shuffle(arr) {
var curIdx = arr.length, tmpVal, randIdx;
while (0 !== curIdx) {
ranIdx = Math.floor(Math.random() * curIdx);
curIdx -= 1;
tmpVal = arr[curIdx];
arr[curIdx] = arr[ranIdx];
arr[ranIdx] = tmpVal;
}
return arr;
}
</script>
</body>
</html>

Categories