I have been stuck on this as I am not the best with mixing arrays + string matches.
What I would like to do is return the index number within an array based on a partial match from a string. Full use case; check if text exists in a URL based off values within an array - and return the index of array position.
Don't mind JS or jQuery but whichever might be most efficient is fine (or works).
Current attempt:
Example URL = www.site.com/something/car/123
Another Example URL might be www.site.com/something/somethingelse/banana/
(location of snippet to match is not always in the same path location)
var pageURL = location.href;
var urlArray = ['/car/','/boat/','/apple/','/banana/'];
function contains(urlArray, value) {
var i = urlArray.length;
while (i--) { if (urlArray[i].indexOf(pageURL)) console.log(i)} console.log('Not Found');}
alternate Using jQuery (not sure where to use indexOf or another jQuery alternative (.search / .contains)):
urlArray.each(function(){
$.each(this, function(index) { } ) });
Expected output for first URL would be 0, second example URL would be 3.
Help is much appreciated!
You can iterate over the array with findIndex() to get the index if the includes() the string.
This will go through the urlArray and return the index of the first match (and -1 if a match isn't found).
let URL1 = "www.site.com/something/car/123"
let URL2 = "www.site.com/something/somethingelse/banana/"
let urlArray = ['/car/','/boat/','/apple/','/banana/'];
let index1 = urlArray.findIndex(str => URL1.includes(str))
let index2 = urlArray.findIndex(str => URL2.includes(str))
console.log(index1, index2)
You can also use a forEach() loop on the urlArray to get each word from the array and check if it exist in url or not.
var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word){
//if word exist in url
var wordIndex = url.indexOf(word);
if(wordIndex !== -1){
console.log(wordIndex);
}
});
NOTE includes() do not work in IE browser and older versions thus to make it work on all browsers the recommended way is to avoid arrow functions with includes() and instead use plain function with indexOf()
To return the array index:
var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word, index){
//if word exist in url
if(url.indexOf(word) !== -1){
console.log(index);
}
});
for (var i = 0; i < urlArray.length; i++) {
if(pageURL .indexOf(urlArray[i])>-1){
console.log(pageURL.indexOf(urlArray[i])));
}
}
Related
I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.
good evening, I am trying to use a single value to search an array, and return the full line the said value is in.
The Array is set up like this in string form:
Xanax,Brand,Anxiety,Code
However, now I'm stuck with calling back only the Medication, and not the full line the Medication is in, sadly. I would like to be able to grab each variable in a line, and make them their own independent variables outside of the array so I can use them for something else.
this.importDataObject("MEDDIAGNOSISICD-10.txt", "C:/Users/dell/Documents/tab
excel/MEDDIAGNOSISICD-10.txt");
var oFile = this.getDataObjectContents("MEDDIAGNOSISICD-10.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
var fileArray = cFile.split('\t');
var Med = this.getField("Medications 1");
var Index = fileArray.indexOf(Med.value);
var Call = fileArray[Index];
console.println(Call);
Any help would be wonderful!
It's because you are running the indexOf method on the whole array, you need to run it on the each value instead. Try a for loop before you check IndexOf method.
Like this:
var i, Index;
for (i = 0; i < fileArray.length; i++) {
Index = fileArray[i].indexOf(Med.value);
if(Index > -1) console.log('Your search is found in ' + fileArray[i] );
}
Note that, in here the variable Index will be 0 or larger if that search is successful. And will be of value -1 if no match is found.
Very close but slightly more complex than this question I have an array and I want to obtain the index of the array of the first occurrence of a value of a given object of this array.
My array has several objects of integer and text, and has an id object of integers (which I call with this instruction wup[i].id).
[edit] The array comes from reading a csv file with header with papaparse.
wup = ["id", "cityName", etc ... ]
[20002, "Tokyo", etc ... ]
[20003, "GoiĆ¢nia", etc ... ]
It is in this id object only that I want to find the input value and finally get the index of this input value. This is certainly using indexOf but how to focus the search only in the id object?
[edit] the instruction that fails is the following (try to find the occurrence of tn[iter].idOri in the array wup, that I expect to retrieve in the variable iOri):
var iOri = wup.indexOf(tn[iter].idOri);
Hoping it is clear enough.
There are lots of ways to do this, map your array down to a flat array of ids:
var myId = 3;
var ids = array.map(function(obj) {
return obj.id;
});
var index = ids.indexOf(myId);
A more succinct (and better - because it only requires one iteration) method would be to use Array.findIndex:
var myId = 3;
var index = array.findIndex(function(obj) {
return obj.id === myId;
});
With es6:
var myId = 3;
var index = array.map(obj => obj.id).indexOf(myId);
or
var myId = 3;
var index = array.findIndex(obj => obj.id === myId);
I have an array that can look like this: ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"]
I want to access the element containing IN, if it exists and the next elements(s) until I reach and including an element with NN in it. and join those elements together into a string.
When I try to access the element containing IN like so, I get -1 that there is no element containing IN.
Here's how I am trying to do it:
strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
strARR[strARR.indexOf('IN')];
but then I get undefined because nothing at -1 exists.
How can I access the element of this array of strings if it contains IN and every element after until it matches an element containing NN, including that element? And joining those as a string?
You need a for loop for that:
var strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
var foundStr = null;
for (var i = 0, cString; i < strARR.length; ++i) {
cString = strARR[i];
if (cString.indexOf("IN") !== -1) {
foundStr = cString;
break;
}
}
if (foundStr !== null) {
/* do someting with found string */
}
strARR[strARR.indexOf('IN')] was returning a weird value because:
strARR.indexOf('IN') // returns -1 (no string "IN" in the array)
strArr[-1] // undefined
There is no "IN" element in that array. Just an "inIN" element, which is not precisely equal. (Keep in mind, this could be an array of ANYTHING, not just strings, so it's not assumed they can check the string contents)
You'll have to loop through the strARR, using a standard for(var i = 0; i < strARR.length; i++) loop. The i variable will help you find the correct indexes.
Then, for combining the results, use the Array.splice and Array.join methods. Splice can take a start index and length of items to take as arguments, and Join can take an intermediate character as an argument, like a comma, to put between them.
You need to evaluate each element in the array individually, not evaluate the array as a whole. Using jQuery each, you can do:
var containsIN = '';
$.each(strARR, function(){
if($(this).indexOf('IN') !== -1){
containsIN = $(this);
}
});
To achieve appending or joining string until you find a string that contains 'NN'
you need to modify the original if condition to:
if(containsIN === '' && $(this).indexOf('IN') !== -1)
then add another condition afterwards
if(containsIN !== ''){
final += $(this);
}
Then, to terminate the each:
if($(this).indexOf('NN') !== -1){
return false;
}
So, the final code should look like:
var containsIN = '';
var final = '';
$.each(strARR, function(){
if(containsIN === '' && $(this).indexOf('IN') !== -1){
containsIN = $(this);
}
if(containsIN !== ''){
final += $(this);
}
if($(this).indexOf('NN') !== -1){
return false;
}
});
You can use the Array's filter() function for this. There is a polyfill available on the linked page if you need to target browsers that do not support filter() natively.
You can create any filter condition that you like and filter() will return the array elements that match your condition.
var strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
var strARRFiltered = strARR.filter(function(element){
return element.indexOf("IN") !== -1;
});
alert(strARRFiltered);
Here is an example of this concept expanded a bit to include accessing multple matches and a variable filter.
To do what you're currently trying to do, the code would need to be like this:
strARR = ["whatWP", "isVBZ", "theDT", "temperatureNN", "inIN", "bostonNN"];
strARR[strARR.indexOf('inIN')];
You need to loop through each element in the array calling indexOf, rather than trying to access it as an array.
I want to find all #tags in a piece of text (using javascript) and use them. The regex myString.match(/#\w+/g) works, but then I also get the #. How can I get only the word without the #?
You can do something like this:
var code='...';
var patt=/#(\w+)/g;
var result=patt.exec(code);
while (result != null) {
alert(result[1]);
result = patt.exec(code);
}
The ( and ) denote groups. You can then access these groups and see what they contain. See here and here for additional information.
var result = myString.match(/#\w+/g);
result.forEach(function (word, index, arr){
arr[index] = word.slice(1);
});
Demo
Note that I'm using ES5's forEach here. You can easily replace it with a for loop, so it looks like this:
var result = myString.match(/#\w+/g);
for (var i = 0; i < result.length; i++){
result[i] = result[i].slice(1);
}
Demo without forEach
Docs on forEach