I have a three strings of categories
"SharePoint,Azure,IT";
"BizTalk,Finance";
"SharePoint,Finance";
I need to find a way to check if a string contains for example "SharePoint" and "IT", or "BizTalk" and "Finance". The tests are individual strings themselces.
How would i loop through all the category strings (1 - 3) and only return the ones which have ALL instances of the souce.
i have tried the following
function doesExist(source, filterArray)
{
var substr = filterArray.split(" ");
jQuery.each(substr, function() {
var filterTest = this;
if(source.indexOf(filterTest) != -1 )
{
alert("true");
return true;
}else
{
alert("false");
return false;
}
});
}
with little success...the code above checks one at a time rather than both so the results returned are incorrect. Any help would be great.
Thanks
Chris
UPDATE: here is a link to a work in progress version..http://www.invisiblewebdesign.co.uk/temp/filter/#
Try this:
function doesExist(source, filter)
{
var sourceArray = source.split(",");
var filterArray = filter.split(",");
var match = true;
$.each(filterArray, function(i, val) {
match = match && ($.inArray(val, sourceArray) != -1);
});
return match;
}
gives doesExist("SharePoint,Azure,IT", "SharePoint,IT")==true but doesExist("SharePoint,Azure,IT", "SharePoint,BizTalk")==false.
you could try something like:
if(filterArray.indexOf("SharePoint") > -1 && filterArray.indexOf("IT") > -1) {
...
}
Related
I'm new to this, so I hope I can explain well enough what my problem is.
I've got a quiz and for an answer I created an input box. To get to another link you have to put two words in there but the order should not matter aka. it shouldn't matter if you write down "word1 word2" or "word2 word1", there should be only one rule: both words should be mentioned.
Is that possible?
My code so far:
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase() == "word1" && "word2"){
window.open("URL","_self");
}
else{
xxx
}
}
It does not work.
Before I only wanted to check if one word is used, like that:
var textwunf_2 = 'word1';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase().indexOf(textwunf_2) == -1){
xxx
}
else{
window.open("URL","_self");
}
}
This worked but I can't use it for two words, because if I write
var textwunf_2 = 'word1 word2';
the order can't be 'word2 word1'...
Is there a solution to my problem?
Hopefully anyone can understand and help me, thank you!
Based on this commentary from the OP:
if the user types 3 words and two of them match with the answer, it should be also okay! even better if even 3 words or more are possible, as long as the user puts my two words in it..
You can check if both words are whitin the text using two conditions on the if:
textwunf_1.toLowerCase().indexOf("word1") >= 0
AND
textwunf_1.toLowerCase().indexOf("word2") >= 0
Try with the next code:
var textwunf_2 = 'word1';
var textwunf_3 = 'word2';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if ((textwunf_1.toLowerCase().indexOf(textwunf_2) >= 0) &&
(textwunf_1.toLowerCase().indexOf(textwunf_3) >= 0))
{
window.open("URL","_self");
}
else
{
// xxx
}
}
Another approach:
var words = ["word1", "word2"];
function CheckWords() {
var inputWords = document.getElementById("wunf").value.split(' ');
var allWordsFound = true;
if (inputWords.length !== words.length) { return false; }
inputWords.forEach(function(word) {
if (words.indexOf(word.toLowerCase()) === -1) {
allWordsFound = false;
return;
}
});
return allWordsFound;
}
console.log(CheckWords());
I am creating a function that receive the text and check if include the answers(xx and yy), it doesn't matter the order. The ans list, can have 1,2 or more words, it will work.
let ans = ['xx','yy'];
function check(text){
text = text.toLowerCase();
let counter = 0;
ans.forEach((x) => {text.includes(x) && counter++ })
return counter === ans.length
}
console.log(check("aa bb")) // false
console.log(check("xx bb")) // false
console.log(check("aa yy")) // false
console.log(check("xx yy")) // true
console.log(check("yy xx")) // true
My knowledge of Javascript & jQuery is very limited but I managed, with some help, to get my autocomplete function where I would like it to be.
I want to limit the results of my autocomplete to any length I want. I know of the following code to limit the results:
source: function(request, response) {
var results = $.ui.autocomplete.filter(airports, request.term);
response(results.slice(0, 10));
}
but my "source" already uses a function to search through certain values & keys within my array for terms:
function airportArray(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(airports, function(value) {
return matcher.test(value.iata) || matcher.test(value.city) || matcher.test(value.airport);
}));
}
How do I add the filter into my already coded function?
JSFIDDLE: https://jsfiddle.net/cgaybba/17p7uyvf/
I've tried many variations, but like I said, my knowledge is limited to combine the two functions successfully.
Any assistance will be much appreciated.
If you're looking to simply filter the results for at most 10 items you can just append the slice function to the returned array from $.grep:
response(
$.grep(airports, function(value) {
return matcher.test(value.iata) ||
matcher.test(value.city) ||
matcher.test(value.airport);
})
.slice(0, 10)
);
Try this:
var cur = 0;
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(
$.grep(airports, function(value) {
var result = matcher.test(value.iata) || matcher.test(value.city) || matcher.test(value.airport);
if (cur >= 10 && result == true) { result = false; } else { cur = cur + 1; }
return result;
})
);
You were already almost there.
I have two array which contains special characters am trying to compare each element of one array to another and get the element which is not found in another array. But my approach doesnt work properly
var specialChar = ['!','#','#','$','%','&'];
var $scope.inp= ['!','*','#'];
In my above example element '*' is not present specialChar
I tried this logic -
$scope.validateChar = function(specialChar,inp){
var i,j;
for (i=0,j=0; i<specialChar.length && j<inp.length;) {
if (specialChar[i] < inp[j]) {
++i;
} else if (specialChar[i] == inp[j]) {
++i; ++j;
} else {
$scope.notFoundChar = inp[j];
Error prompt showing special charatcter $scope.notFoundChar not found
$scope.charAllowedText = false;
return;
}
}
}
Please suggest what am doing wrong here?
You can filter out your Special char '*' like below
var result=[]
inp.map(function(inpElement){
if(specialChar.indexOf(inpElement)==-1)
result.push(inpElement)
})
console.log(result)
Below given code solves your problem.
var source = [1,2,3,4,5,6,7,8];
var target =[2,3,4,5,6,18,19];
var missingItems = [];
target.forEach(function(itemFromTarget){
var itemFound = false;
source.forEach(function(itemFromSrc){
if(itemFromTarget === itemFromSrc){
itemFound = true;
}
});
if (!itemFound) {
missingItems.push(itemFromTarget);
}
});
console.log(missingItems);
I'm trying to figure out a challenge in Free Code Camp which states the following:
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
I understand how to do this if the 2nd string has a single character or if the 1st string has the 2nd string contained in the exact same sequence (e.g. "hello", "hel" and not "hello", "olleh"). But I can't figure out yet the correct approach to tackle this challenge.
Here is my code...
function mutation(arr) {
var myArray = arr.splice(1).toString().toLowerCase();
var splicedArray = arr.toString().toLowerCase();
if (splicedArray.search(myArray) != -1) {
return true;
} else {
return false;
}
}
Any combination which has a different sequence of the characters evaluates to false.
// e.g this is false
mutation(['Alien', 'line'])
What is the right way to complete this task?
Thanks to #Bergi I figured out the answer. Also he was so kind to allow me to post the answer myself. Here it is...
function mutation(arr) {
var string2 = arr.splice(1).toString().toLowerCase();
var string1 = arr.toString().toLowerCase();
for(var i = 0; i < string2.length; i++) {
if (string1.indexOf(string2.charAt(i)) == -1) {
return false;
}
}
return true;
}
If someone like me (JS beginner) encounters this task and finds this solution, here are some notable resources to read through if you do not know the methods used here..
.splice()
indexOf()
.slice()
Difference between .slice() and .splice() methods
You could also do this:
/**
* Match function that operates on a data array with two elements, where the
* first element is the query and the second element is the searchable data.
*
* Returns true if the query string contains all of the letters of the searchable
* data string.
*
* #param {Array} data - contains query and searchable string data
*
* #return {Boolean} if a match occured
*/
var match = function (data) {
// Convert strings to arrays.
var query = Array.prototype.slice.call(data[0]);
var searchableData = Array.prototype.slice.call(data[1]);
// Every query string character should occur in the searchable data.
return query.every(function (search) {
// Only some of the searchable data characters should occur in the query data.
return searchableData.some(function (target) {
return search === target;
});
});
};
match([ 'abc', 'xyzadefbhijc' ]); // returns true
match([ 'abq', 'xyzadefbhijc' ]); // returns false
My mutation
function mutation(arr) {
var string2 = arr[1].toLowerCase();
var string1 = arr[0].toLowerCase();
for(var i = 0; i < string2.length; i++) {
if (string1.indexOf(string2.charAt(i)) == -1) {
return false;
}
}
return true;
}
The same can be done using map:
function mutation(arr) {
var one = arr[0].toLowerCase();
var two = arr[1].toLowerCase().split('');
var match = true;
two.map(function(val){
if(one.indexOf(val) === -1){
match = false;
}
});
return match;
}
function mutation(arr) {
var src=arr[0].toLowerCase();
var dist=arr[1].toLowerCase();
for(var i=0;i<dist.length;i++){
if(src.indexOf(dist[i])<0) return false;
}
return true;
}
console.log(mutation(["voonoo", "no"]))
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});