access elements in array of strings that contain certain strings - javascript

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.

Related

JavaScript Clearing Array Value

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.

Find index number of array value based on partial string match

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])));
}
}

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

how to find specific objects and put them in an array in javascript

I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/

Storing part of regex using javascript match

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

Categories