What I’m trying to do is select an option based on the url. So what I have done so far is get the url and match it to the options. Then stored the matches in an array, next I removed a few terms like ‘http’,’org’, etc.. I was able to narrow it down to two keywords.
Now what I have to is select an option that match one of the keywords in the array.
I tried to use ‘filter’, contains: and map but it only work if I’m using one term and the array, I have an array of terms. So what I need to know how to do is select and option based on the first match. From the text of the option to the term in the array.
//this is my arr
var arr = ["Pro_life", "Inactive"]
//this is the text from the options
FB_Ext_Pro_life_Specific_Inactive
FB_register_now
i need to find a way to select 'FB_Ext_Pro_life_Specific_Inactive' with a term from my array.
Anyone have any ideas?
I didn't get your question completely, but i managed to make this
var arr = ["Pro_life", "Inactive"]
var options = ["FB_Ext_Pro_life_Specific_Inactive", "FB_register_now", "sample_Inactive__"]
for (var x = 0; x < arr.length; x++) {
for (var y = 0; y < options.length; y++) {
if (options[y].indexOf(arr[x]) != -1) {
console.log("Option " + options[y] + " matches with " + arr[x]);
}
}
}
It uses indexOf() for checking if the keyword matches with the option
May be you can do like this;
var arr = ["Pro_life", "Inactive"],
str = "FB_Ext_Pro_life_Specific_Inactive\nFB_register_now",
result = str.split("\n")
.filter(s => arr.some(k => s.indexOf(k) !== -1));
console.log(result);
Related
My problem is as follows: I am trying to take data as formatted in the 'names' variable in the snippet below, convert the string to array, then reorganize the array so the text is in the correct order. I am able to get the pieces I have put together to properly sort the first or last instance of a first & last name, but am seeking guidance on how to go about processing multiple names. The snippet below will return the last instance of the first & last name in the correct order. At this point, I am only looking to have the data returned as a properly sorted array, e.g.
if the input string is
names = "Bond, James & Banner, Bruce";
once processed should return: ['James', 'Bond,', '&', 'Bruce', 'Banner,']
As always I appreciate all the help I can get, thanks in advance!
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
idx = i;
}
}
namesArr.move(idx, idx+1);
console.log(namesArr);
You were close but this solution should work for you. Basically you need to update in the loop and increment the index i to account for the switch. Otherwise you will end up revisiting the first last name you switch.
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce & Guy, Other";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
namesArr.move(i, i+1);
i++;
}
}
console.log(namesArr);
Another solution could be by using String.prototype.match() and a regular expression \w+ to match the names:
var names = "Bond, James & Banner, Bruce & Licoln, Anna"; // ...
var arr_names = names.match(/\w+/g); // Match names
var res = [];
for (var i = 0; i < arr_names.length; i += 2) { // Step by 2
res.push(arr_names[i + 1]); // Push the name before
res.push(arr_names[i]); // Push the current name
res.push("&"); // Add "&"
}
res.splice((res.length - 1), 1); // Remove last "&"
console.log(res);
I have a given word, that I want to match against a given list of words, mainList, and establish which words of that given list are anagrams of the given word, and add them to another list, subList.
I feel like my method to do this is fine, but it returns an unexpected result.
For example...
var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];
var subList = [];
Then I take the word, split to an array of letters, alphabetise, and join back into a string. With this string I should be able match against any possible anagrams (which I will covert in the same way).
var mainSorted = [];
for (i = 0; i < word.length; i++) {
mainSorted = word.split('').sort().join();
}
This is where it goes wrong. I loop through the mainList array trying to establish if a given item, when converted, matches the original. If so, I want to push the word to the subList array.
for (var i = 0; i < mainList.length; i++) {
var subSorted = mainList[i].split('').sort().join;
if (mainSorted === subSorted) {
subList.push(mainList[i])
}
}
return subList;
...and the value I expect to see for subList is: ['stream', 'maters']
Yet I am returned an empty array instead.
I've gone through this so many times and I cannot see what's going wrong, would really appreciate some help!
Also, I'm aware there's probably more eloquent methods to do this (and I welcome any suggestions) but primarily I want to see where this is going wrong.
Thanks in advance.
You forgot () at the end of join
var subSorted = mainList[i].split('').sort().join;
should be
var subSorted = mainList[i].split('').sort().join();
One non-issue is
for (i = 0; i < word.length; i++) {
mainSorted = word.split('').sort().join();
}
doesnt need to be in a loop
mainSorted = word.split('').sort().join();
alone suffices
as a bonus, here's a tidier way of doing what you are doing
var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];
var mainSorted = word.split('').sort().join();
return mainList.filter(function(sub) {
return sub.split('').sort().join() == mainSorted;
});
I'm a beginner with javascript, and after searching I am still running into an error with this part of my code.
I have an array:
var choices = [ '$5/hr', '$6/hr', '$7/hr', '$10/hr' ];
And I want to use a regular expression to return the array as integers so I can use it for further calculations. I know that replace only works on strings and not an array so I have tried the following:
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
EDIT: Apparently the issue is somewhere else in my code. Maybe this needs to be wrapped in another function?
Here is the function that this resides in. This function receives an array as a value and will calculate an average using the array received and the choices array which I cannot convert to integers.
// Choice values
var ul = document.getElementById('Results');
var choices = [];
// Get li element choices
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
choices.push(ul.childNodes[i]);
}
}
// Strip the last element in array since it is the result container.
choices.splice(-1,1);
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
Thanks!
The issue is that you are pushing the nodes in your array, not their text content. Try this instead:
choices.push(ul.childNodes[i].textContent)
or:
choices.push(ul.childNodes[i].childNodes[0].nodeValue)
I have an array of records. I want to search a string at the specific position of the array. But some how I am not able to do so. Kindly see the code below:
var match_index = [];
var count = 0;
var keyword1 = csvvalue[1][9].replace(/\"/g, '');
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
$("#index").html("loop");
var keyword1 = csvvalue[i][9].replace(/\"/g, '');
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
In the above code, the control is is not going inside the if statement, though the string is available in the array at index 1 and 2. Also only the last value of i is getting printed (last line of the code) though it should print all the values of i starting from 0.
My actual requirement is to search through entire array for a specific string. I have changed the code to suit my requirement better.
Edited
I tried every thing but the control is not going inside the if statement though there are two matching records
You are comparing two values set before the loop
I guess it should be more like :
var match_index = [];
var count = 0;
var keyword1 = "";
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
keyword1 = csvvalue[i].replace(/\"/g, '');
$("#index").html("loop");
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
Or depending on how your csvvalue array is structured.
keyword1 = csvvalue[1][i].replace(/\"/g, '');
Why loop through the whole array if you want to check a specific variable in the array.
You could just do something like
if (search_text === csvvalue[1][9].replace(/\"/g, '') {
//do something
}
Unless you really need to know how many times you run through the array.
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.