The if statement doesnt work in my forloop - javascript

Currently I am working on Java script project.the project is for Checking the values selected from a UDDF file with the whole values in the UDDF file.But the if statement used for comparison is not working.I have put my code below
function parseUddf(){
var myArray=new Array("null","airportID","airportSiteNo","faaRgn","uddfVer","null","airportName","verificationDate",
"city","state","horizontalelevationdatum","horiAccuracy","elevAccuracy","orthoDatum","orthoAccuracy",
"magDec","verificationDate","airportOrthoElev","airportEllipsoidElev","airportElevationLoc",
"verificationDate","towerFloorOrthoElev","towerFloorEllipElev","verificationDate","arpLatitude","arpLongitude");
var selt=document.getElementById("textdis").value;
var x = document.getElementById("uddf").value;
x = x.split("#");
var x0 = x[0];
x0 = x0.split("|");
var j=x0.length;
alert(j);
for(var i=1;i<x0.length;i++){
alert("selt="+selt.toString());
if(selt.toString()==x0[i])
{
alert("success");
alert("i="+i);
alert(myArray[i]);
//document.getElementById("textdistitleid").value=myArray[i];
break;
}
}
}
the UDDF file values are:
|FAI |50219.A |AAL |1.07|
|FAIRBANKS INTERNATIONAL AIRPORT |1592011|
|FAIRBANKS |ALASKA |
|NAD83 |5 CM |15 CM |NAVD88 |25 CM |
|-20.4|1592011|
| 439.0| 470.0|20R+3990|1592011|
| 529.0| | |
| 644854.4|-1475123.2|
I need your help

Instead of using == you can use .equals():
selt.toString().trim().equals(x0[i].trim())
You can get your trim() function for javascript from here

Related

Google Script: Searching with a cell value

I want to add +1 to a value from a customer.
As example:
| G8 | K8 |
| Max Mustermann | 140 |
Goal:
| G8 | K8 |
| Max Mustermann | 141 |
I have a Script that works fine, but I would like to use the value (Max Mustermann) from a cell (G5).
function TextFinden() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
spreadsheet.getRange("G8:G" + spreadsheet.getLastRow()).createTextFinder("Max Mustermann").matchEntireCell(true).findNext().offset(0, 4).activate();
//value +1
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var value = cell.getValue() * 1;
cell.setValue(value+1);
}
Goal example:
createTextFinder("G5")
So, I can write the Name in a cell (G5) and use a Button to add +1 to the Customer.
Any advice will be appreciated, thanks.
I believe your goal is as follows.
You want to retrieve a value from cell "G5".
You want to search the value from cells "G8:G".
When the value is found, you wan to add 1 to the column "K" of the same row.
In this case, how about the following sample script?
Sample script:
function myFunction() {
const sheet = SpreadsheetApp.getActiveSheet();
const value = sheet.getRange("G5").getDisplayValue();
const range = sheet.getRange("G8:G" + sheet.getLastRow()).createTextFinder(value).matchEntireCell(true).findNext();
if (!range) return;
const valueRange = range.offset(0, 4);
valueRange.setValue(valueRange.getValue() + 1);
}
Note:
If the value of column "K" is the string value, please modify valueRange.setValue(valueRange.getValue() + 1) to valueRange.setValue(Number(valueRange.getValue()) + 1)
References:
createTextFinder(findText) of Class Range
offset(rowOffset, columnOffset)

How to use a JavaScript variable's in a "each" iteration on Pug (Jade)

(If the following question has English errors, tell me and I'll correct them.)
Hey, I have to do a project using Pug, I've done everything but now I'm stuck because I have to get a variable from the pug render to use it and show only 1 row when I click on the change button of my list.
At the start of my code, there's a script part with a function getValue,
script(src='book_list.js')
script
| function getValue(value){
| const hello = document.getElementById("test")
| $('#exampleModalLong').modal('show')
| hello.innerHTML = value
| window.test = value
| console.log(hello)
| alert(window.test)
| console.log(hello.innerHTML)
| }
When I use the function, the hello.innerHTML is printed on the console, but when I use the same document.getElementById("test").innerHTML, it makes an error.
each book in message
- var testISBN = document.getElementById("test").innerHTML;
if !{testISBN} != book.isbn
each val in book
p
hr
hr
img(src="", alt="")
label.col-form-label(for='recipient-name') #{val}
input#recipient-name.form-control(type='text' value=`${val}`)
And the result is :
58| .form-group
59| each book in message
> 60| - var testISBN = document.getElementById("test") .innerHTML;
61| if !{testISBN} != book.isbn
62| each val in book
63| p
Cannot read property 'getElementById' of undefined
Also can someone tell me if I used the unescaped string interpolation correctly in the line below ? Thanks for your help

Get First Row where ColA = Name, ColB = SecondName and ColC = null(is empty)

I'm very new to JavaScript so bear with me. I want an equation that searches multiple columns for specified values, not the same value across all columns. For example: ColA = James , ColB = Smith, ColE = ""(cellisempty) right?
Once it finds the first Row with that criteria, it gets that row to be used in another equation which would be setValue(ColE + gotRow, new Date()) I'm making a Time in/Time Out Sheet if you are curious. The Idea is the function searches for a person's name and for the next available space to place the time because the same person may have signed out and in multiple times on the same sheet. Once he has the row with an empty spot it places in the current time on that row, which makes it no longer empty, meaning next time the function runs, it will skip that row and go to the next one the guy signed out of.
here is a function I was given to try out my problem thanks to one of the Users.
function getValue(cellName) {
return SpreadsheetApp.getActiveSpreadsheet().getRange(cellName).getValue()
}
function setValue(cellName, value) {
SpreadsheetApp.getActiveSpreadsheet().getRange(cellName).setValue(value);
}
function rowWhereTwoColumnsEqual(value1,col1,value2,col2) {
var value1=value1;//testing
var value2=value2;
var col1=col1;//testing
var col2=col2;//testing
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var rA=[];
for(var i=0;i<vA.length;i++) {
if(vA[i][col1-1]==value1 && vA[i][col2-1]==value2) {
rA.push(i+1);
}
}
Logger.log(rA.push(i+1))
SpreadsheetApp.getUi().alert(rA.join(','));
}
I created a function below it, just for inputting values to see how it works
function getrowWhereTwoColumnsEqual(){
rowWhereTwoColumnsEqual('James','Sheet1!A',null,'Sheet1!C')
Logger.log(rowWhereTwoColumnsEqual('Ta','Sheet1!A',null,'Sheet1!C'))
}
The sheet I made has 'James' in A1 while C1 is empty. It also has 5 other rows full of random names.
Column A | Column B | Column C
=================================
James | C |
Kyle | E |
Micheal | T |
Sarah | K |
Tray | F |
John | D |
So I was expecting to get a response "1" because row 1 should be true for both, but instead I saw "7". Probably because Row 7 is blank in all columns so all columns equal the same. So I must have entered the values wrong, or the equation needs an adjustment. Like I said, I'm very new.
Edit 5/9/19 20:06
Thank you again Cooper. Your function works pretty well.
function test() {
findRows(1,getValue('A1'),2,getValue('B1'),3,null,'Sheet1')
Logger.log(findRows(1,getValue('A1'),2,getValue('B1'),3,null,'Sheet1'));
}
However, once I added values to C1, logger.log came up []
Column A | Column B | Column C
=================================
James | C | 5/9/19
Kyle | E |
James | T |
Sarah | K |
James | F |
John | D |
without the value, I received [1.0,3.0,5.0], but once I changed a value I received [] was expecting [3.0,5.0]
Edit 9:00 PST
I Changed the null to "" and it seems to be working.
Edit 9:25 PST
Final Equations function Test() is the one that was finished product and succeeded.
function getValue(cellName) {
return SpreadsheetApp.getActiveSpreadsheet().getRange(cellName).getValue()
}
function getValues(cellName) {
return SpreadsheetApp.getActiveSpreadsheet().getRange(cellName).getValues()
}
function setValue(cellName, value) {
SpreadsheetApp.getActiveSpreadsheet().getRange(cellName).setValue(value);
}
function findRows(c1,n1,c2,n2,c3,n3,name) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(name);
var rg=sh.getDataRange();
var vA=rg.getValues();
var rA=[];
for(var i=0;i<vA.length;i++) {
if(vA[i][c1-1]==n1 && vA[i][c2-1]==n2 && vA[i][c3-1]==n3) {
rA.push(i+1);
}
}
return rA
}
function test() {
var passiveRow = findRows(1,getValue('A2'),2,getValue('B2'),3,"",'Sheet1');
Logger.log(passiveRow);
setValue('C' + passiveRow, new Date().toLocaleString());
}
In order for "" to work Row 1 must have a header. It Only works if there is only 1 result, which there should be in the end. it finds the name and a blank spot to put the date.
Try this:
c1,c2 and c3 are column number n1,n2 and n3 are values or strings or null and name is the sheetname.
function findRows(c1,n1,c2,n2,c3,n3,name) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(name);
var rg=sh.getDataRange();
var vA=rg.getValues();
var rA=[];
for(var i=0;i<vA.length;i++) {
if(vA[i][c1-1]==n1 && vA[i][c2-1]==n2 && vA[i][c3-1]==n3) {
rA.push(i+1);
}
}
return rA
}
function test() {
Logger.log(findRows(1,10,2,2,3,null,'Sheet150'));
}

How Do I Use Both Math.max() and Math.min() to bound my dragger

I'm building a horizontally dragging page layout. There are 3 columns, with two dragging objects. Everything is working fine except setting a max/min value for the drag.
The layout looks like this, with the two dragging bars either side of colB.
---------------------------
colA | colB | colC
| |
| |
| |
| |
| |
| |
| |
| |
I need to set it so that colA's dragger's maximum width (which is its left value) is equal to colC's dragger. Likewise, ColC's minimum needs to be colA's draggers' left value.
The function looks like this:
function doDragA(e) {
dragA.style.left = (e.clientX) + 'px';
}
function doDragC(e) {
dragC.style.left = (e.clientX) + 'px';
}
and I'm trying to do something like this:
function doDragA(e) {
var posC = parseInt(document.defaultView.getComputedStyle(dragC).left, 10);
dragA.style.left = (math.max(posC), math.min(0)) e.clientX + 'px';
}
function doDragC(e) {
var posA = parseInt(document.defaultView.getComputedStyle(dragA).left, 10);
dragC.style.left = (math.max(0), math.min(posA)) e.clientX + 'px';
}
But i'm getting syntax errors. I've console logged the values and they come through, it's just the math max/min syntax I'm getting wrong.
Firstly javascript is case sensitive, and the math object is Math, not math.
Secondly, the usage of min and max is to supply a list of arguments, not just one - it returns the answer to 'what is the value of highest/lowest of these?'.
Assuming you want the value of e.clientX bounded by some values valueMax and valueMin:
var valueUpToMax = Math.min(valueMax, e.clientX);
var valueAtLeastMin = Math.max(valueMin, e.clientX);
// so we can combine those to bound on both sides:
var boundedValue = Math.max(valueMin, Math.min(valueMax, e.clientX));
It seems like they should be the other way around; we limit to a maximum value by using Math.min, but it's because we are limiting to a maximum not trying to get a maximally high number.
The general principle is to use functions like in math:
c = f(a, b);
e = g(c, d);
-> e = g( f(a, b), d);

Cubic Regression (best fit line) in JavaScript

I'm having the worst time trying to find a JavaScript code that could allow me to do cubic regressions. Would write it myself, but my understanding of polynomial math is, well, suboptimal.
So, here's what I'm looking for. Given an input of an array of arrays, where the internal array would be [x,y], the function would give me an output in the form of an array with four parameters - [a,b,c,d], where a, b, c, and d are parameters of the equation y = ax^3 + bx^2 + cx + d.
Example:
Input is an array like this [[2,5],[5,10],[07,15],[12,20],[20,25],[32,30],[50,35]].
Which essentially is the representation of a table:
| x | y |
|-----------------|
| 02 | 05 |
| 05 | 10 |
| 07 | 15 |
| 12 | 20 |
| 20 | 25 |
| 32 | 30 |
| 50 | 35 |
Now, the output would be [0.000575085,-0.058861065,2.183957502,1.127605507]. These are the a, b, c, and d parameters of the cubic function.
(FYI, the output I got by using Excel's LINEST function and running it on the above set of numbers using an array function {1,2,3}).
How could this be done? Huge thanks in advance for any guidance.
Best,
Tom
Here's a real, working bit of code to solve that cubic using the numeric.js library's uncmin unconstrained minimiser as a least squares problem (jsbin here):
var data_x = [2,5,7,12,20,32,50];
var data_y = [5,10,15,20,25,30,35];
var cubic = function(params,x) {
return params[0] * x*x*x +
params[1] * x*x +
params[2] * x +
params[3];
};
var objective = function(params) {
var total = 0.0;
for(var i=0; i < data_x.length; ++i) {
var resultThisDatum = cubic(params, data_x[i]);
var delta = resultThisDatum - data_y[i];
total += (delta*delta);
}
return total;
};
var initial = [1,1,1,1];
var minimiser = numeric.uncmin(objective,initial);
console.log("initial:");
for(var j=0; j<initial.length; ++j) {
console.log(initial[j]);
}
console.log("minimiser:");
for(var j=0; j<minimiser.solution.length; ++j) {
console.log(minimiser.solution[j]);
}
I get the results:
0.0005750849851827991
-0.05886106462847641
2.1839575020602164
1.1276055079334206
To explain: we have a function 'cubic', which evaluates the general cubic function for a set of parameters params and a value x. This function is wrapped to create the objective function, which takes a set of params and runs each x value from our data set through the target function and calculates the sum of the squares. This function is passed to uncmin from numeric.js with a set of initial values; uncmin does the hard work and returns an object whose solution property contains the optimised parameter set.
To do this without the global variables (naughty!), you can have an objective function factory thus:
var makeObjective = function(targetFunc,xlist,ylist) {
var objective = function(params) {
var total = 0.0;
for(var i=0; i < xlist.length; ++i) {
var resultThisDatum = targetFunc(params, xlist[i]);
var delta = resultThisDatum - ylist[i];
total += (delta*delta);
}
return total;
};
return objective;
};
Which you can use to manufacture objective functions:
var objective = makeObjective(cubic, data_x, data_y); // then carry on as before
Knowing how to do this practically would be of great help to a lot of people, so I'm glad this has come up.
Edit: Clarification on cubic
var cubic = function(params,x) {
return params[0] * x*x*x +
params[1] * x*x +
params[2] * x +
params[3];
};
Cubic is being defined as a function which takes an array of parameters params and a value x. Given params, we can define a function f(x). For a cubic, that is f(x) = a x^3 + b x^2 + c x + d so there are 4 parameters ([0] to [3]), and given those 4 param values we have a single function f(x) with 1 input x.
The code is structured to allow you to replace cubic with another function of the same structure; it could be linear with 2 parameters:
var linear = function(params, x) {
return params[0]*x + params[1];
};
The rest of the code will look at the length of params in order to know how many parameters need modifying.
Note that this whole piece of code is trying to find the set of parameter values which produce a curve which best fits all the data; if you wanted to find a fit for the last 4 points of some data, you would pass only those values in data_x and data_y.
I'd formulate this as a least squares problem. Let M be the n×4 matrix formed like this:
x_1^3 x_1^2 x_1 1
x_2^3 x_2^2 x_2 1
⋮ ⋮ ⋮
x_n^3 x_n^2 x_n 1
Then compute the 4×4 matrix A=MT⋅M and the 4×1 column vector b=MT⋅y and solve the linear system of equations Aξ=b. The resulting vector ξ will contain your coefficients a through d.
The above description makes it easy to understand what is going on, mathematically. For implementation, particularly for very large n, the above approach might however be infeasible. In those cases, you can build A and b directly, without explicitely constructing M. For example, A1,2=sum(x_i^3 * x_i^2 for all i). So you can iterate over all i and add the corresponding values to the corresponding matrix and vector entries.

Categories

Resources