JavaScript - Printing from Array of Objects Not Working - javascript

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}

What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

Related

JavaScript to remove string in OBX 5.1 starting with first occurance of "\\." till the end

I am trying to write a JavaScript to remove string in OBX 5.1 after "\."
Here is the inbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||
Here is the expected outbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2|x 10^9/l|4 - 10|L|||F|||||
I have written this Javascript code. It is compiling but not removing the unwanted text.
Here is what I have written:
var RegExp_pattern = "\\.";
function indexOf(stringToTrim) {
return stringToTrim.indexOf(RegExp_pattern);
}
function substring(ssstringToTrim) {
return ssstringToTrim.substring(indexOf(OBX_TestValue), -1);
}
/* Single input message case */
var next = output.append(input[0]);
// loop through Order Group (OBR) & Result Group (OBX)
//
var cntObs = next.getRepeatCount("ObservationMessage");
for (var i = 0; i < cntObs; i++) {
var cntOrders = next.getRepeatCount("ObservationMessage[" + i + "]/Order");
for (var j = 0; j < cntOrders; j++) {
var cntResults = next.getRepeatCount("ObservationMessage[" + i + "]/Order[" + j + "]/Results");
for (var k = 0; k < cntResults; k++) {
var OBX_TestValue = next.getField("ObservationMessage[" + i + "]/Order[" + j + "]/Results[" + k + "]/OBX/ObservationValue");
if (OBX_TestValue.indexOf(OBX_TestValue) > 0) {
OBX_TestValue = substring(OBX_TestValue);
}
}
}
}
To remove everything from the first occurance of "\." until the end of the string you should use a regular expression.
var str = "OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||";
var mtch = str.replace(/\\\..*/, '');
console.log(mtch);

Why is not working when i try to add a to a string to my array location

I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS
var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
secondArray[i] = getFirstname();
window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
if(i % 2 === 0) // index is even
{
even2.push(secondArray[i]);
for ( var i=0 ; i<even2.length; i++)
even2[i]+=" Chavez"
}
else
{
odd2.push(secondArray[i]);
for ( var i=0 ; i<odd2.length; i++)
odd2[i]+=" McCain"
}
}
document.write(" \n all the names: "+ secondArray+'<br>');
document.write(" \n even names: "+ even2+'<br>');
document.write(" \n odd names: "+ odd2+'<br>');
The problem is that you are making a second loop that is unnecessary... the code
for ( var i=0 ; i<even2.length; i++)
and
for ( var i=0 ; i<odd2.length; i++)
should be simply removed.
You need to add first or last name only to last element added to odd2 or even2 and this can be done with:
even2[even2.length-1]+=" Chavez"
and
odd2[odd2.length-1]+=" McCain"
It is important to get used adding correct indentation because this kind of error is much easier to spot in the code when it is properly indented.
You don't need to loop again to add the specific last name. You can just prepend it while you are inserting it into the array like below.
var numberfirstNames = 5;
var userMessage = " Please enter a first Name";
var secondArray = [];
var odd2 = [];
var even2 = [];
// loop 5 times LOOP ASKING FOR "5" FIRST NAMES >> STORING IN NAMES
for (var i = 0; i < numberfirstNames; i++) {
secondArray[i] = getFirstname();
window.alert("second " + secondArray[i]);
if (i % 2 === 0) {
even2.push(secondArray[i] + " Chavez");
} else {
odd2.push(secondArray[i] + " McCain");
}
}
document.write(" \n all the names: " + secondArray.join(",") + '<br>');
document.write(" \n even names: " + even2.join(",") + '<br>');
document.write(" \n odd names: " + odd2.join(",") + '<br>');

Join letters to 1 word

I'm playing around with PEG.js.
This is my grammar:
start = expression
expression = a:[a-z]+
{return a.join("");}
When I execute it in my browser:
obj = parser.parse("test");
for (var i = 0; i <= obj.length; i++) {
console.log(i + " - " + obj[i])
}
I get this output:
0 - t
1 - e
2 - s
3 - t
4 - undefined
Why isn't it joined to only 1 word, even though I used return a.join("") in my grammar?
parser.parse does return the single word "test"; you are just printing it one character at a time.
Did you mean to do this?
var result = parser.parse("test");
console.log(result) // "test"
To directly answer your question, you're getting one letter each iteration because a string acts like an array. So you're accessing one letter at a time by using obj[i] Try this to get one word returned.
obj = parser.parse("test");
for (var i = 0; i <= obj.length; i++) {
console.log(i + " - " + obj)
}

Match a range of rows in an array? jQuery, Javascript

I'm unsure how else to write the title but it's about as close as I can get to what I'm after.
I have a calculator I'm trying to create that compares values in a number of arrays.
Each data object in my array has 34 rows, some of which have the same number/value in them.
At the minute if you select france, I only want 1 of each grade to show in the dropdown, so the number 1 would appear once.
If you select France and grade 1, I want the outputted value to say the lowest value in that range to the highest, in this case USA would output 3 to 5 does this make sense?
If so I'm wondering how I'd possibly do this?
JSFiddle
http://jsfiddle.net/R85Qj/
Does this help?
http://jsfiddle.net/R85Qj/2/
$("#convert").on("click", function () {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
/* gradeConversion += "<span>" + countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "</span>";*/
var indexes = [];
var countryIndex = $("#country").val();
var gradeValue = countryGrades[countryIndex].grades[gradeIndex][0];
// find all indexes of gradeValue
for(var i = 0; i < countryGrades[countryIndex].grades.length; i++) {
if (countryGrades[countryIndex].grades[i][1] == gradeValue) {
indexes.push(i);
}
}
allValues = [];
for(var c = 0; c < countryGrades.length; c++) {
gradeConversion += countryGrades[c].country + ":";
for(i = 0; i < indexes.length; i++) {
if (i == 0 || countryGrades[c].grades[indexes[i]][1] != countryGrades[c].grades[indexes[i-1]][1]) {
gradeConversion += countryGrades[c].grades[indexes[i]][1] + " ";
}
}
}
$("#conversions").html(gradeConversion);
});

Google Apps Script: How to fix this for loop to insert paragraphs of one google document to another?

So I'm arriving at last stops of my Apps journey (there'll be several others =).
The code bellow is a function that aims to do this: iterates through the paragraphs of one google text document and, when it finds in text some sinal, some paragraph (such as "Introduction", "Part 1 - Background" or "Part 2 - Biography") whose content is igual a theses_type, it inserts all theses_type paragraphs into the first document, after that sinal or theses_type keyword.
So, I'm trying to do this with the function "importTheses" (thanks #Serge insas and others for previous help!). But I'm having trouble after the line for( var k = 0; k < thesesParagraphs-1; ++k ). Even when I got through the log the boolean True, I can't get the paragraphs inserted. I also can't get the log of this line: Logger.log("thesesDoc.getText() = " + thesesElement.getText() );. So, any help or hint will be very appreciated.
function importTheses(targetDocId, thesesId, thesesType) { // just a name, I used it to analyse docs
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDoc.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
Logger.log("targetDocId = " + targetDocId);
Logger.log("thesesId = " + thesesId);
Logger.log("thesesType = " + thesesType);
var elTargetDoc=[];
var elTheses=[];
for (var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
Logger.log("targetDoc.getChild(j) = " + targetDocElement);// to see targetDoc's content
elTargetDoc[j]=targetDocElement.getText();
if(elTargetDoc[j] == thesesType){
Logger.log("elTargetDoc[j]== " + elTargetDoc[j]);
Logger.log("thesesType " + thesesType);
Logger.log("if(elTargetDoc[j]== thesesType)" + (elTargetDoc[j]== thesesType) );
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
Logger.log("thesesDoc.getChild(k) " + thesesDoc.getChild(k));
Logger.log("thesesDoc.getText() = " + thesesElement.getText() );
elTheses[k] = thesesElement.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
for( var k = 0; k < thesesParagraphs-1; ++k ) { .. }
In this line of code, you're intention is to loop using k, over integer values starting at 0. The loop should run at least once, as long as thesesParagraphs is 2 or more... and is a number.
That second condition is your problem. Earlier in the function, you had this:
var thesesParagraphs = thesesDoc.getParagraphs();
... so thesesParagraphs is an Array of Paragraph objects, not a number. You are probably interested in the count of paragraphs:
for( var k = 0; k < thesesParagraphs.length-1; ++k ) { .. }
^^^^^^^
Or perhaps thesesElements was what you intended to use to bound your loop, since it's a number.

Categories

Resources