I have two html datalists, and I get their input values to query a json file. I first search the keys of my json file which are college majors, their values are their courses. So once the object key equals the program, I return that element because I want to further query that element with the second input field which is a course number. This step is always successful at returning the correct program courses corresponding to the program input.
The second step is where things go bad. I want to now take that program element and look through all the names of the courses in that program. I concatenate the two input fields, program + " " + course. The program is a major like "CSE" or "I S" and the course is any 3 digit number like "143" or "310". Each object element in the program has a string name attribute like "CSE 143". This name attribute does not equal the program + " " + course even though they are both of type string and the same value WHEN I am looking at a program that has a space in it. For example, I want to find the course "I S 310". I successfully search for the program name that equals "I S". I iterate through the keys and find the correct element value using this operation Object.keys(jsondata[index]) == program. program is a variable containing the string "I S". As stated previously, this is successful, but if I iterate through the children of that objectkey value to find id, like programdata[index].children == program + " " + course, it doesnt work. If I instead hardcode the value, programdata[index].children == "I S 310", it works! This leads me to believe that the concatenation operation for these two variables changes the encoding of the string. According to console.log, the type of "I S 310" and program + " " + course are both Strings except they output a different encodeURIComponent().
Ill write what the output to the console is since im not reputable enough:
Step 1
function getProgramCourses(data, program) {
var programKeys = Object.keys(data);
for (var i = 0; i < programKeys.length; i++) {
if (Object.keys(data[i]) == program) {
return data[i][Object.keys(data[i])];
}
}
return objs
}
program = "CSE"
console.log(program)
console.log(encodeURIComponent(program));
Output:
CSE
CSE
program = "I S"
console.log(program)
console.log(encodeURIComponent(program));
Output:
I S
I%C2%A0S
Those unencoded hidden characters dont affect this first step of finding the courses offered by the "I S" program. Now when I want to find a specific course within the "I S" program like "I S 310":
Step 2
//data is object array of all courses in this program
function getCourse(data, program, course) {
pc = program + " " course;
for (var i = 0; i < data.length; i++) {
if (data[i].name == pc) {
return data[i];
}
}
}
"CSE" = program and "143" = course
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
CSE 142
CSE%20142
["I S" = program and "310" = course][2]
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
I S 310
I%C2%A0S%20310
This second step only works for programs that dont have spaces like "CSE" or "MATH". Doesnt work for "A A" or "I S". data[i].name is type String and so is pc.
Sorry about the lengthy post, I just wanted to be as descriptive as possible. Any help would be greatly appreciated.
Basically
Here is my problem:
console.log("A A 198")
console.log(encodeURIComponent("A A 198"))
console.log(program + " " + course)
console.log(encodeURIComponent(program + " " + course))
Output:
A A 198
A%20A%20198
A A 198
A%C2%A0A%20198
not equal
Your program variable contains a character which is like a space but isn't a space. Make sure it isn't an encoding issue, else you can fix this with this simple code.
encodeURIComponent(program.replace(/\u00a0/g, ' ') + ' ' + course)
Related
Actually I think there is an even better way to get the prices using this npm (you can open it to see better how it works):
https://github.com/jaggedsoft/node-binance-api than using the "coin "variable I am trying to use but I don't know how it could be possible, if you guys could help me to figure out with a better idea or the best way to pull prices with this package using discord it would be awesome, I've been already some days sticked to it :/
What I need:
To be able to replace "ticker.XRPBTC" (code below).
For example if I write ETH it should be changed from ticker.XRPBTC to ticker.ETHBTC
var coin = (message.content.toUpperCase()).slice(2) + "BTC";
binance.prices((error, ticker) => {
console.log("Price of " + coin + ":", ticker.XRPBTC);
});
for that I made the variable coin, I thought I could just write ticker.coin but it does not work...
I have tried this:
As an example:
ticker.XRPBTC - This code works, output: the actual price of the currency.
What I am trying:
var coin = XRPBTC
console.log(ticker.coin) - output: undefined
btw. I am writting console.log to test it in the console but I also have an error if I write:
if (msg.startsWith ("eth")) {
message.reply ("Price of " + coin + ":", ticker.TRXBTC);
}
an explanation of what ticker does:
The ticker has the function to get the last price of each currency, it can be for example ETHBTC, XRPBTC, TRXBTC etc. in this case eth, xrp and trx are the currencies. So in the ticker I just need to write it that way so that I can get the price for that pair.
As you can see in the code I sent you above, I am getting the text exactly how the ticker would "need it to look".
So if I write eth, the variable "coin" is transforming it into ETHBTC
Best!
I think you're looking for property access. You might want to check if the coin exists first, e.g.
var coin = message.content.toUpperCase().slice(2) + "BTC";
console.log(coin); // logs e.g. "ETHBTC"
binance.prices((error, ticker) => {
if (coin in ticker) {
var price = ticker[coin]; // <- property access
message.reply("Price of " + coin + ": " + price);
} else {
// handle error, e.g.
message.reply("Coin " + coin + " doesn't exist");
}
});
I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be many ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
Not only did you confuse yourself, but you crashed the browser! :-)
(The for loop never terminates because you push a new value to the list on every iteration.)
I could tell you what's wrong with the code in more detail, but you'll learn a lot more if you chase it down yourself. So what you need now is to learn the art of debugging.
Add a debugger statement at the beginning of your test() function:
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
debugger;
var info = prompt("hi " + input + " what is your name?");
for(i=0; i< list.length; i++){
if( info === list.length[i]){
console.log(list[i]);
}
else{
list.push(info);
}
console.log(list);
}
}
Now run test() and it will stop in the debugger at that statement. Look at the different panels in the debugger - you can view your variables and other stuff. Find the place where it has controls to let you step through your code. Single-step through the code and look at the variables as you go. You will soon discover what the problems are. In most browsers there are also keyboard shortcuts to let you step through the code more easily.
If you use Chrome, here is an introduction to the Chrome DevTools. There are similar tutorials for the other browsers too.
heres an algorithm :
Use an object to store the user no. and the count. like :
{"222":"3","444":"1"}
this means 222 has visited 3 times and 444 visited once. now every time a user checks in:
see if the key with the user's number exists, if yes increment the count. if no, add a new entry with count = 1.
check if the number is 5, if yes get free coffee and reset count to zero. skip if no.
I would solve the problem by storing the visit count in a dictionary that maps each customer's ID to the number of times they have visited. The dictionary is initially empty. When you look up an ID in the dictionary for the first time, you'll get undefined, which tells you that you must initialize the value.
The following demonstration has a couple of buttons that you can use to make Alice or Bob visit the shop. Click on the blue button at the bottom to start the demo.
function message(s) { // Simple output for a code snippet.
document.getElementById('display').innerHTML += s + '<br />';
}
var coffeeCount = {}; // Stores the number of visits by each customer.
function customerVisit(id) { // Called when a customer visits.
if (coffeeCount[id] === undefined) { // Check for first visit.
coffeeCount[id] = 0; // Initialize the visit count.
}
var count = ++coffeeCount[id]; // Increment the visit count.
message(id+': '+count+' visit'+(count == 1 ? '' : 's'));
if (count % 5 == 0) { // Check for free coffee.
message('→ Free coffee for customer '+id+'!');
}
}
<button onclick="customerVisit('Alice')">Alice</button>
<button onclick="customerVisit('Bob')">Bob</button>
<div id="display"></div>
Try including utilization of input elements; set visits count as value of property id, info at object list; call test with value of input element : id ; or at prompt : info . At five visits , display coffee , reset value of id to 0.
var list = {
"111": 0,
"222": 0,
"333": 0,
"444": 0,
"555": 0,
"666": 0
};
var test = function test(id) {
coffee.innerHTML = "";
var info;
if (id.length > 0 && !/^(\s)/.test(id)) {
if (list.hasOwnProperty(id)) {
++list[id];
} else {
list[id] = 1;
}
info = confirm("hi " + id + " this is your " + list[id] + " visit");
} else {
info = prompt("hi, please enter an id");
if (!!info && !/^(\s)/.test(info) && list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
} else {
info = prompt("hi, please input a different id");
if (!!info && !/^(\s)/.test(info) && !list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
}
};
alert("please try a different id")
};
for (var id in list) {
if (list[id] === 5) {
alert("hi " + id + ", thanks for visting " + list[id] + " times");
coffee.innerText = "☕";
list[id] = 0;
break;
}
};
console.log(list);
};
var inputs = document.querySelectorAll("input");
var coffee = document.getElementById("coffee");
coffee.style.fontSize = "5em";
inputs[1].onclick = function(e) {
test(inputs[0].value)
};
<input type="text" placeholder="please enter id" value="" />
<input type="button" value="click" />
<div id="coffee"></div>
n is number of costumer
Initially array is [0,0,0,.....n times]
All values are 0 because no costumer has visited the shop.
For n=5 array would look like
var a=[0,0,0,0,0];
1)To solve this problem in array.
2)Suppose we have array of size n.
3)then index of the array will be 0...n-1
4)So we can map id of costumer to the index.
5)And value will keep count of the number of visit for the index.
6)a[5]=11; here 5 is index and 11 is value
7)For our problem if customer with id i we increment a[i]=a[i]+1 if he visits .
8) Then we can check
if(a[i]+1 === 5) {
console.log("Custumer "+ i + " get a free coffee");
a[i]=0;
}
else {
a[i]=a[i]+1;
}
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be manyt ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
I will give you a short function to check how many times a specific value is at the array:
function countHowManyTimesAValueIsOnArray(arr, valueToCheck){
return arr.filter(function(arrayValueToCompare){
return arrayValueToCompare === valueToCheck;
}).length
}
Attention for the use of '===' instead of '=='. This will compare the value considering its type. 222 will not be found as "222"
No need to complicate things here's an simple way, just add a count function that search how many times user has enter
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
var info = prompt("hi " + input + " what is your name?");
var check=0;
for(i=0; i< list.length; i++){
if( info === list[i]){
check=1;
break;
}
}
list.push(info);
if(check==1){
count(info);
}
}
function count(info){
var count=0;
for(i=0; i< list.length; i++){
if(list[i]===info)
count++;
}
console.log(count);
}
}
I am trying to basically check if the string ends with ", " then do not append another ", " . If the string does not end with ", " then append ", ". I just want one ", " in between two strings. However as I hit the "compute" button of my script several times (which basically iterates the key values & appends the comma's between strings) , I get multiple ", " between two strings. What I tried does not really work.
eg:
Expected is abc, apple, pear, strawberry
even if I hit compute many times or one time
What I get after multiple clicks of compute button:
abc, , , , apple, , , , pear, , , , strawberry
Here's what I tried:
//Here obj[key][i] is the string
var lenson = obj[key][i].length;
if(1!=len-1){
if(obj[key][i].charAt(lenson-1) === " " && obj[key][i].charAt(lenson-2)=== ","){
}
else{
if(obj[key][i]!=""){
obj[key][i]+=", ";
}
}
li.appendChild(document.createTextNode( obj[key][i] ));
}
I am assuming you are getting your data from some sort of json object or similar. Since you are already looping over the keys, my advice would be to simple store them in an array. Then when you want to output them to string you just use .join(",")
var list = yourarray.join(",");
my name's Mike and my question is two-fold:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm trying to make a simple flashcard program to help me memorize different kinds of sound equipment. The list of equipment is large but I'm only including three different kinds to keep this example simple. I want each object to have two properties: answer and desc. This first part defines three objects, places them in an array, creates a variable for picking one of the array items randomely, and another variable for prompting the user for an answer:
var newFlash = function() {
var A827 = {
answer: "T",
desc: "Multitrack Tape Recorder"
};
var LA2A = {
answer: "O",
desc: "Classic Leveling Amplifier"
};
var SonyC800G = {
answer: "M",
desc: "Tube Condenser Microphone"
};
var list = [A827, LA2A, SonyC800G];
var rand = Math.floor(Math.random() * list.length);
var question = prompt("What kind of equipment is " + list[rand] + "?");
};
Now, if I make my three items in my array all strings, they show up no problem in the question prompt correctly replacing list[rand] with the appropriate array item. However, using objects in my array, my prompt says "What kind of equipment is [object Object]?.
My end goal is for the user to enter the appropriate one- or two-letter response (M for Microphone, C for Console, O for Outboard Gear, T for Tape Machine, S for Software, and CH for Computer Hardware) where upon entering the successful letter(s) yields an alert that displays both the object's answer and desc. My n00b instinct tells me this second part should be an if/else statement in the form of
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
}
else {
alert("Wrong, try again.");
}
but I'm very certain that this isn't the right way to access these object properties.
So, again, my question has two parts:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm sure some piece of logic is escaping me. Thanks for reading.
You want to use var question = prompt("What kind of equipment is " + list[rand].desc + "?");. list[rand] will yield you an object which has the structure {answer: "", desc: ""}, so you need to additionally access the description in your code.
Similarly, you want:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
}
else {
alert("Wrong, try again.");
}
To access the property of an Object in Javascript you use dot notation, as is common with many languages that have Objects. list is an array of Objects, so when you type list[rand] you are returning one of those Objects. Once you have an Object, you simply need to use the dot notation to access whatever property it is you require, in this case either desc or answer.
So instead of
var question = prompt("What kind of equipment is " + list[rand] + "?");
try
var question = prompt("What kind of equipment is " + list[rand].desc + "?");
Placing the property you are trying to access outside the bracket. This solves your second question as well, simply change:
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
to:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
this fiddle will help demonstrate.