For loop condition issues - javascript

I am having troubles figuring out the for condition for a javascript learning course I am doing.
I am not getting normal errors because I am doing it in the course, but the error I am receiving in the course is this...
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.
These are the instructions:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
for(var i = 0; // rest of loop setup
your second should be something like
for(var j = i; // rest of loop setup
Second, think hard about when your loop should stop. Check the Hint if you get stuck!
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
This is my code
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; i < myName.length; i++) {
hits.push();
}
}
}
I know the issue resides in this line:
for (var j = i; i < myName.length; i++) {
I just can't figure out exactly how I need to structure it.
UPDATE:
Final answer of question:
/*jshint multistr:true */
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(myName);
}
}
}
if (hits === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

I'll give you the solution because you can learn more from the direct solution than from banging your head on that one.
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var equal = true;
for (var j = 0; j < myName.length; j++) {
if (text[i + j] != myName[j]) {
equal = false;
break;
}
}
if(equal) hits.push(myName);
}
}
There may be other ways to reach this result. This is one of them.
Explaing what "push" does:
Arrays are lists of variables. You store a value in a variable like this:
var myNumber = 777;
var myName = "Nelson";
An array declaration looks like this:
var myNumbers = [];
then you put something inside of it, like this:
myNumbers.push(333);
myNumbers.push(555);
myNumbers.push(777);
then if you try: console.log(myNumbers), it will print: [333, 555, 777]
if you add another push:
myNumbers.push(999);
will add 999 to the list resulting in [333, 555, 777, 999]
Check this demo
got it ? take a look here to more detailed explanation:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Am not sure what you are trying to achieve,
Here is something may help
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var res = '';
for (var j = i; j < i+myName.length; j++) {
res = res+text[j];
}
if(res == myName)
{
hits.push(myName);
}
}
}
console.log(hits);
Here is demo

Related

Return global array element

I am trying to simply print out a global array list of students that I have imported from a csv file. I've done enough troubleshooting to know that the data is being imported and read fine. The common answer seems to be that you don't require a "var" declaration for a global array but this wasn't working for me either.
Here is my declaration:
//Student array list from csv import
studentList = [];
//window.studentList = [];
This is where I initialize the array:
function processData(csv){
let allLines = csv.split(/\r\n|\n/);
for(let i = 0; i < allLines.length; i++)
{
let row = allLines[i].split(",");
let col = [];
for(let j = 0; j < row.length; j++)
{
col.push(row[j]);
}
if(col == " ") break;
studentList.push(col);
}
//when I alert the array element by element the data is being read from within this function
for(let i =0; i < studentList.length; i++)
{
alert(studentList[i]);
}
}
But if I was to use a get method to return the elements I would get an 'undefined' error
function getStudent(index) {
return studentList[index];
}
for(let i = 0; i < studentList.length; i++)
{
alert(getStudent[i]);
}
EDIT: Despite that solution being right, I still have the same issue when calling from another function. For example in the following I need to return the trip departure for each student which is undefined.
function getStudentsDeparture(i)
{
trip.departure = getStudent(i);
alert(trip.departure); //prints undefined
trip.destination = "123 Smith Rd, Maddingley VIC 3340";
console.log('dest is: ' + trip.destination + ' dept is: ' +
trip.departure);
}
The issue seems to be that you try to get an index from the function getStudent[i]. Try change that row to alert(getStudent(i)); with parenthesis.
EDIT
I tested with this code and it works fine for me
studentList = [];
studentList.push('student1');
function getStudent(index) {
return studentList[index];
}
function getStudentsDeparture(i) {
var student = getStudent(i);
alert(student);
}
getStudentsDeparture(0);

search an string array using given user and return indexes of the matched string array

I have this array.
var possibleValues=["contacts","delete","new contact","add","display"];
user input can be "contacts" or "how to create a contact?".my function must return index as 0,2 which has a phrase contact in it.I am trying a logic but i cant find.What have i done currently is
var indexes = [];
for (i = 0; i < possibleValues.length; i++) {
if (arr[i].indexOf(userinput) != -1 || userinput.indexOf(arr[i])!=-1) {
indexes.push(i);
}
}
Someone can help me out in this issue
Your code is almost correct. But you have to compare with -1, not 1. And you're using arr[i] instead of possibleValues[i].
And if you want to match each word in the user input, you need to split it up, and add another nested loop.
var possibleValues = ["contacts", "delete", "new contact", "add", "display"];
var userinput = "how to create contact";
var words = userinput.split(' ');
var indexes = [];
for (i = 0; i < possibleValues.length; i++) {
for (var j = 0; j < words.length; j++) {
if (possibleValues[i].indexOf(words[j]) != -1 || words[j].indexOf(possibleValues[i]) != -1) {
indexes.push(i);
break;
}
}
}
console.log(indexes);

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.

loop different arrays javascript

Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.

jQuery dynamically increment variable name inside a for-loop

is it possible to add i to a var inside a for-loop?
in wrong syntax it would look like the code below
for(i=1; i<=countProjects; i++){
var test + i = $(otherVar).something();
};
Thanks!
It would be best to use an array for this:
var test = [];
for (i = 1; i <= countProjects; i++) {
test[i] = $(otherVar).something();
};
Then you could access the values like this:
console.log(test[1]);
console.log(test[2]);
etc...
If you have really good reason to have named variables for each value, you can create them like this:
for (i = 1; i <= countProjects; i++) {
window["test" + i] = $(otherVar).something();
};
console.log(test1);
As Mat stated, you should be using arrays for this type of functionality:
var projects = [];
for (var i = 0; i <= countProjects; i++) {
projects.push($(otherVar).something());
}
You could craft variable names, using object["varname"] syntax. But it's _generally_ bad practice:
var varName;
for (var i = 0; i <= countProjects; i++) {
varName = "test" + i.toString();
this[varName] = $(otherVar).something();
}
console.log(test1);

Categories

Resources