I have a gigantic list (800 items) and one really long string. I want to get the first item in the array that matches the part of the string and stored in a variable.
My code currently:
for (var i = 0; i<gigantic_genre_array.length; i++) {
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre != -1) {
tag1 = gigantic_genre_array[test_genre];
alert(tag1);
}
}
This doesn't work like I thought it would, any suggestions?
Try this:
for(var i = 0; i<gigantic_genre_array.length; i++){
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre!=-1){
tag1 = gigantic_genre_array[i];
alert(tag1);
}
}
Do the process reversely it will be efficient too.
var wordArray = thelongstr.split(' ');
for(var i=0,len = wordArray.length; i < len; i++)
{
if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
{
alert(wordArray[i]);
}
}
You may create a RegExp based on the array and test it against the string:
var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';
alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar
Related
I have written a function called reverseStr that takes in a string as a parameter and returns the string but with the characters in reverse.
For example: reverseStr('bootcamp'); => 'pmactoob'
Following is my program:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0; i <= splitStr.length -1 ; i++)
{
for(var j = splitStr.length - 1; j >= 0; j--)
{
reverseString[i] = splitStr[j]
}
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
If I run the function reverseStr("bootcamp") it returns bbbbbbbb.
Does anyone see a problem with the code?
Note: I DONOT WANT TO USE REVERSE() BUILT-IN FUNCTION
However, I found success with the following code but still need an answer to my initial question
function reverseStr(str)
{
var splitStr = str.split("");
reverseStr = "";
for(var i = splitStr.length - 1; i >= 0 ; i = i - 1)
{
reverseStr += splitStr[i];
}
return reverseStr;
}
You don't need to double-iterate through the characters, i.e., do not need to nest for loops. Iterate once and grab the chars in reverse order, like this:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0, j=splitStr.length-1; i <= splitStr.length -1 ; i++, j--)
{
reverseString[i] = splitStr[j]
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
You can see that here the loop goes on for as long as i <= splitStr.length -1,ie, length of the string. This is sufficient to get the mirroring character (i versus Array.length-i).
Here is a working snippet to demo:
var reverseStr = function(str) {
let result = String();
for(let i = str.length-1; i >= 0; i--) {
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
Perhaps a more elegant way to achieve the same (apart from Array.prototype.reverse()) would be to use String.prototype.chatAt(). This would avoid two conversions to and from an array, and also save you one variable. Granted, the code is much shorter and more obvious in what it is doing.
var reverseStr = function(str) {
let result = String(); // An empty string to store the result
for(let i = str.length-1; i >= 0; i--) { // Iterate backwards thru the chars and add to the result string
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''); // Original return method of the author
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
The problem is that your nested for loop runs its whole course before it returns to the outer for loop. So, it just repeats one character the amount of times equal to the length. Instead of having another for loop, just add a simple counter for j like j++ inside your outer for loop and use that value with the i value.
To the original poster, consider this:
If you know the length of the original string, you therefore know the offset of that last position within the original string.
Iterate through the original string in reverse order, appending the current position's value to a new string. The new string would be the reverse of the original.
Aydin's example is essentially correct. Here's my very similar version, with comments:
function reverseString(inputString) {
// create a new empty string
var newString = "";
// iterate through the characters of the string in reverse order,
// appending to the new string
for (var i = inputString.length - 1; i >= 0; i--) {
newString += inputString[i];
}
return newString;
}
console.log(reverseString('bootcamp'));
I am having an array with string:
var dict =["johndoe","johnrte","jahnaoi"];
I want to make a function (with regex or other) to check if "str" with missing letter fit one of its item. Missing letter is represented by "#".
Let's say that the string with missing letter is "j#hn#oe".
I started that way, but I think I am not going to right way.
function Checkword(str) {
// Check were is the #
var indices = [0]
for (var i = 0; i < str.length; i++) {
if (str[i] === "#") indices.push(i);
}
var regexel = "/^";
for (var index = 0; index < indices.length; index++) {
regexel.concat(str.substring(indices[index - 1], indices[index]));
regexel.concat("[a-z]");
}
regexel.concat("$/");
var reg = new Regex(regexel);
for (r = 0; r < dict.length; i++) {
if (reg.test(dict[r]) {
console.log(dict[r]);
}
}
}
Checkword("j#hn#oe");
In this case, it would return first and last item.
*** Edit after comment:
Which word should pass my test:
If str is j#hndo#=> dict[0], dict[2].
If str is j####### => dict[0], dict[1], dict[2];
IF str is Jonh#oe=> dict[0]
if str is a#ze#ts=> nothing.
Thanks to the comment, this is the answer which is a lot more easier than expected. Thank you!
var dict =["johndoe","johnrte","jahnaoi"];
var dict =["johndoe","johnrte","jahnaoi"];
function ismissing(str){
while(str.indexOf("#")>0){
str=str.replace('#', '[a-z]{1}');
}
var reg=new RegExp(str);
console.log(reg);
for(i=0;i<dict.length;i++){
if(reg.test(dict[i]))
{console.log(dict[i])};
}
}
ismissing("j#hn#o#");
output=>
/j[a-z]{1}hn[a-z]{1}o[a-z]{1}/
johndoe
jahnaoi
undefined
Basically, I have a multidimensional array that I need to build into a simple string.
Quite an easy question, although it has been eating away at me for quite some time now since I can't seem to nail it.
Here is an example of how my array could look with just 3 questions within it:
[["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]]
For example, D.rows[0][0] would be "question1" and D.rows[2][3] would be "answer3", just to clarify.
Here is how it must be saved into a string as:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
Each element must have a comma between them, and each question must be separated by a line-break.
This is what I currently have that is not working:
var fullString;
for (i = 0; i < csvArray.length; ++i)
{
second = secondArray[i];
for (j = 0; j < second.length; ++j)
{
fullString += entry[j] + "'";
}
fullString += "\n";
}
Thanks in advance!
try this
var s,a=[["question1","answer1","answer2","answer3","answer4"],"question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
for(i=0; i < a.length; i++){
s=(s)?s+"\n\r"+a[i].join():a[i].join();
}
jsfiddle example
In your own example: since you are going straight to adding to fullString, it should have an empty string for value, otherwise you will end up with undefined in the beginning.
var fullString="";
this part second = secondArray[i]; should have been
var second = csvArray[i];
and in a same way this fullString += entry[j] + "'"; should have been
fullString += second[j] + ",";
one liner:
var result = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]].join('\r\n');
something like this:
var questionAnswerSet= { "question1" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
"question2" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
}
and access like this:
questionAnswerSet[0].answer2 // question one answer 2
questionAnswerSet[1].answer2 // question two answer 2
for (var i=0; i<yourArray.length; i++) { // iterate on the array
var obj = yourArray[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}
If you have an array as this...
var arr = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
then...
var strArr = arr.join(',');
var strLine = arr.join('\n'); // string with line breaks.
will do that for you.
if you want different strings for each question-answer block, then...
var strJoinArr = [], strJoinLines = '';
for(var i = 0; i < arr.length; i++){
strJoinArr.push(arr[i].join(','));
strJoinLines += arr[i].join(',')+ '\n'; // string with line break
}
then to access each section you can use indexes,
For example, strJoinArr[2] will return 'question3,answer1,answer2,answer3,answer4'
more on .join()
more on .push()
This might be your solution if you plan ot change separators or number of answers.
var array = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]],
string = "";
for (var i = 0; i <= array.length - 1; i++) {
string +=array[i].join(', ');
string += "\n";
}
Also, in the less readable but also effective way, for any object of this structure
string = array.join('\r\n');
I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.
I'm attempting to search a string for another string given by the user.
My code so far is:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;
var sourceSearch = function(text) {
for(i = 0; i < source.length; i++) { //for each character in the source
if(source[i] === searchString[0]) { //if a character in source matches the first element in the users input
one = source.indexOf(i); //confused from here on
for(p = searchString.length; p > 0; p--) {
}
}
}
};
sourceSearch(searchString);
My idea was:
check to see if the first loop finds a character that matches the first character in the user input
if it matches, check to see if the next X characters after the first match the next X characters in the source string
if they all match, push them to the hits array
My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.
Any ideas would be helpful. Thanks very much in advance.
Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.
You can try:
if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}
As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:
var sourceSearch = function(text) {
var i, j, ok; // always declare your local variables. globals are evil!
// for each start position
for(i = 0; i < source.length; i++) {
ok = true;
// check for a match
for (j = searchString.length - 1; ok && j >= 0; --j) {
ok = source[i + j] === searchString[j];
}
if (ok) {
// searchString found starting at index i in source
}
}
};
This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString.
This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).
to follow your approach, you can just play with 2 indexes:
var sourceSearch = function(text) {
j = 0;
for(i = 0; i < source.length; i++) {
if(source[i] === text[j]) {
j++;
} else {
j = 0;
}
if (j == text.length) {
console.log(i - j); //this prints the starting index of the matching substring
}
}
};
These answers are all pretty good, but I'd probably opt for something like this:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;
This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}