Javascript, check if input is in array - javascript

I am new to javascript and struggling with the use of arrays.
I am trying to check if user input value is in an array I declared called fruits. If it is I want to execute code. If it is not I want an alert displayed. I tried using the
instanceof
method to check the value but the code doesn't execute any of the if else statement. Any ideas as to why?
$("#submit-btn").bind("click", function() {
var comment = $("#comments");
var commentValue = $.trim(comment.val());
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
if (commentValue.length === 0) {
alert('Comments are required to continue!');
}
else if (commentValue instanceof fruits){
execute code
});
}
else {
alert('not a valid fruit');
}
return false;
}
});

Your first if should be outside the for loop.
Inside you simply change the else if to
if(commentValue === fruits[index])
And then you move the code inside the else out after the for loop.
A simpler way of doing it would be:
if (commentValue.length === 0) {
alert('Comments are required to continue!');
return false;
}
if(fruits.indexOf(commentValue) > -1) {
execute code
return false;
}
alert('not a valid fruit');
return false;

Try indexOf(), if indexOf return anything bigger then -1, you have match
like this:
else if (commentValue.indexOf(fruits[index]) > -1){

Related

Comparing two arrays in a class with a loop

I am trying to compare two arrays without using any built in 'compare' functions. I'm getting stuck on how to format the loop to run ( the i >= my_arr.length part) because I feel like part of my issue might be there. I keep getting true even when the two arrays are different. This is a function I'm writing inside of a class. Thanks in advance
is_equal(other_arr){
let result=[];
for(let i =0; i >= my_arr.length; i++){
if(MySet[i] === other_arr[i]){
return true;
}else{
return false;
}}}}
I'd change it around slightly like this:
is_equal(other_arr){
if (my_arr.length != MySet.length) return false;
for(let i =0; i >= my_arr.length; i++){
if(MySet[i] !== other_arr[i]){
return false;
}
}
return true;
}
The function you have written returns true on the first equal element contained in the Arrays. Try the code below:
is_equal(other_arr){
let result=[];
for(let i = 0; i < my_arr.length; i++){
if(MySet[i] !== other_arr[i]){
return false;
}
}
// If the 'for loop' is over, all elements are equal, only then is true return
return true;
}

Arrays in arrays, length always is 0, json not working

I try to create arrays in arrays and then forward it to JSON.
First problem, when i try to use a lista.length or something, console always return 0. I tried to overpass this problem and create another array, but now I have problem with JSON - always return [] - empty lista array.
var lista = [];
var licz = [];
function ListujBledy(value, where) {
var checked = document.getElementById(value).checked;
var desc;
if (value == "blad-tab") {
desc = "Nieprzeźroczysta lista graczy.";
} else if (value == "blad-tab1") {
desc = "Brak listy graczy na początkowym zrzucie ekranu.";
} else if (value == "blad-tab2") {
desc = "Brak listy graczy na końcowym zrzucie ekranu.";
}
if (checked == true) {
if (lista[where] == undefined) {
var temp = [];
temp[value] = desc;
lista[where] = temp;
licz[where] = 1;
} else if (licz[where] == 1) {
var temp = lista[where];
temp[value] = desc;
lista[where] = temp;
licz[where] = 2;
} else if (licz[where] == 2) {
var temp = lista[where];
temp[value] = desc;
lista[where] = temp;
licz[where] = 3;
}
} else {
if (licz[where] == 1) {
delete lista[where];
licz[where] = 0;
} else if (licz[where] == 2) {
delete lista[where][value];
licz[where] = 1;
} else if (licz[where] == 3) {
delete lista[where][value];
licz[where] = 2;
}
}
console.log(lista.length);
console.log(lista);
console.log(JSON.stringify(lista));
console.log("---------------------------------------------------------");
}
Console log from browser:
I don't have more ideas, I can't use lista[0], lista[1] etc. everything must be functional. Eveyrthing is taken from variables but everywhere I was looking for information about it, everybody using numbers in key or permanent keys.
Editied version of code:
I know that checked could have been better done, so I corrected it here.
https://jsfiddle.net/5vdgLtue/1/
The main problem is that even if I do this https://jsfiddle.net/5vdgLtue/0/ the array returns this element, but the length function says it is 0.
It looks like you might be starting out with javascript. Keep in mind that you haven't actually called the function at any point in your code. Is that the case or are you not sharing the full code you have run?
There is only one condition in which the array 'lista' could gain value: if 'check'== true and 'where' == undefined.
In that scenario, you declare the array 'temp' and declare temp[value]= desc. However, if 'value' contains a value different than "blad-tab", "blad-tab1" or "blad-tab2", 'desc' remains empty therefore temp[value] has a name but no value. You are then assigning a named valueless item to lista[where] which would explain why your console displays content but no length. btw, this would be easier if you named your variable something other than 'value' .
Problem is your selector points to the parent element. In jquery you could do this less code but assuming you're not using jQuery. Try something like:
function getDesc(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
//or use getElementsbyClassName...
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
for (var i=0; i<checkboxesChecked.length; i++) {
if (checkboxesChecked[i].value === "blad-tab") {
desc = "Nieprzeźroczysta lista graczy.";
} else if (checkboxesChecked[i].value === "blad-tab1") {
desc = "Brak listy graczy na początkowym zrzucie ekranu.";
} else if (checkboxesChecked[i].value === "blad-tab2") {
desc = "Brak listy graczy na końcowym zrzucie ekranu.";
}
}
return desc;
}
This should answer most of your questions.
In summary:
In javascript there are 2 types of arrays: standard arrays and associative arrays
[ ] - standard array - 0 based integer indexes only
{ } - associative array - javascript objects where keys can be any strings
What you are doing is using array in an associative manner. Basically, you are adding properties to your array objects, unlike a standard array where you would only assign values by zero-indexed numbers like temp[0]='something', lista[1]='some other thing' etc.
If you want the length of the key set of the array, then you can use Object.keys(lista).length. This should solve your problem.

searching for value in an array with a for loop in javascript

I am searching for an value from an array in javascript and this is my code.
HTML
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Javascript
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
for(i=0; i<arr.length; i++) {
if(txtval.value==arr[i]) {
alert("match found for " + txtval.value)
}
else {
alert("its not there")
}
}
}
At the moment, I keep getting alert saying "its not there" when I enter "dog". It prints "its not there" twice and then prints "match found for dog".
I would like the alert to show only if the word does not exist in the array. I know it is doing this because I have the if statement in the for loop and each time if the index of the array does not match, it shows the alert. But how do I do it?
You're alerting on every pass of the loop. Instead, use a flag and alert at the end:
function arraycheck () {
var found = false; // *** The flag
for (var i=0; !found && i<arr.length; i++) {
// ^^^^^^^^^---- *** Stop looping if we find it
if (txtval.value==arr[i]) {
found = true; // *** Set the flag, it was found
}
}
if (found) {
alert("match found for " + txtval.value);
} else {
alert("its not there");
}
}
or we could just use the result of the == directly:
function arraycheck () {
var found = false; // *** The flag
for (var i=0; !found && i<arr.length; i++) {
// ^^^^^^^^^---- *** Stop looping if we find it
found = txtval.value==arr[i]; // *** Set the flag if it was found
}
if (found) {
alert("match found for " + txtval.value);
} else {
alert("its not there");
}
}
(Side note: Unless you're declaring i somewhere you haven't shown, your code is falling prey to The Horror of Implicit Globals [that's a post on my anemic little blog]. Declare your variables. I've added declarations for i in the examples above.)
However, there's already a function for that (two, in fact): includes (on newer JavaScript engines) and indexOf (on older ones):
function arrayCheck() {
var found = arr.includes(txtval.value); // <===
if (found) {
alert("match found for " + txtval.value)
} else {
alert("its not there")
}
}
or the found part of that on older browsers using indexOf:
var found = arr.indexOf(txtval.value) != -1;
In a comment you asked:
I was wondering if you could also stop the loop in my code using "return"?
Yes, that's yet another way to do it in this specific case, since exiting the function (with return) exits the loop:
function arraycheck () {
for (var i=0; i<arr.length; i++) {
if (txtval.value==arr[i]) {
alert("match found for " + txtval.value);
return;
}
}
alert("its not there");
}
You can simplify using indexOf method,
if(arr.indexOf(txtval.value) > -1)
DEMO
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
if(arr.indexOf(txtval.value) > -1)
{
alert("match found");
}
else {
alert("its not there");
}
}
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Try the following with Array's includes() in a more simpler and cleaner way:
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
if(arr.includes(txtval.value)){
alert("match found for " + txtval.value)
}
else{
alert("its not there")
}
}
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Create a variable that will turn to true when a match is found. Then if after the loop the variable is still false, then no match has been found.
Or better yet, use lodash filter. It simplifies the looping process.
You can try to find the index of your txtval.value in the array by using JavaScript Array indexOf() method.
It takes a input value and output the index number of that value in the Array if the value exists.
As javascript array index starts from 0, so if the value exists, the method will return integer(index in the array) value that is greater than -1.
So, in your case,
function arraycheck () {
var index = arr.indexOf(txtval.value);
if(index > -1){
//alert for found match
}else{
//alert for no match found
}
}

alert() window appears for every element in an array when looping?

I am trying to make some kind of search function, where a pop-up would appear and ask for an input from the customer and then compare it to the array items and return another alert window with either "found" or "not found"
Here is my code for the specific function:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.prompt("found");
} else {
window.prompt("not found");
}
}
}
It is kind of working. The problem is that it keeps showing a new alert window for every single element in the array. For example if I have 6 elements in the array and only one is matching the search input, then it will show me 5 alert windows with "not found" and one with "found". Another one appears after i close the previous one or if I click the ok button. How do I make it show me the alert window only once to tell me if it found it or not? Thanks!
Put the alert (not prompt) after the loop. Also need to switch to using a variable to track whether or not the item was found:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
break;
}
}
window.alert(found ? 'found' : 'not found');
}
Instead of showing the alert every time, set a variable such as var found=true. After loop terminates then show alert based on status of that var.
To show alert only once you have to execute the alert after loop ends, not inside loop.
Since you aren't doing anything else in your function after the loop, you can simply return when you find the element you were looking for. And only display the "not found" if you finish the loop without finding the element.
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.alert("found");
return;
}
}
window.alert("not found");
}
You could also simplify this by using Array.prototype.indexOf or Array.prototype.includes
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
}
}
if(found == true)
window.prompt("found");
else
window.prompt("not found")
}
you are telling it to show the message every time it finds one, if you are seeking to finding only 1 match then just terminate the loop when you find it.
End the loop using break; or simply just set i to the arrays length:
......
if (model.items[i] == searchInput) {
window.prompt("found");
return 0;
}
.....
window.prompt("Not found"); //if fucntion doesn't return then it's not found.
OR
var found = false;
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
break;
}
.....
if(!found) window.prompt("Not found");
OR
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
i = items.length;
}
.....
if(!found) window.prompt("Not found");

Including a for loop in an if statement

I'm building an application in which I want to display some errors when a user enters invalid values in an input box. A correct value is appended as 'entry' to a div if no errors were found. In total there are 3 cases when to display errors:
The input value is empty
The input value is a number
The input value already exists
These errors are displayed with if else statements.
1.and 2. were easy, but the problem case (3.) only validates against the first element of class .cat_entry.
if(cat_input == '') { // generate errors
errorDisplay(error_input_empty);
} else if(!isNaN(cat_input)) {
errorDisplay(error_input_number);
} else if($('.cat_entry') == cat_input) { // THIS IS THE PROBLEMATIC LINE
// .cat_entry is the class of the entries that have been appended
errorDisplay(error_duplicate);
} else {
// stuff
};
So I believe I need a for loop/ .each() (no problem so far), but how do I include this as a condition in an if statement? Something like.. if( for(i=0;i<$('.cat_entry').length;i++) { ... }; ... How to return true (or something similar) when one of the entries matches the input value, then pass the return value to the if statement?
EDIT: here is a jsFiddle with the relevant code. I updated it with $.inArray() method. I'd like to try and use this instead of a for / .each() loop.
You can try this:
var a=$('.cat_entry'),o={};
for(i=0;i<a.length;i++) {
var s=a[i].val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
or
var o={};
$('.cat_entry').each(function(){
var s=$(this).val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
You can actually use the jQuery inArray function for this, such as:
else if($.inArray(cat_input, $('.cat_entry') != -1)
}
The solution was to add this to the function:
var isDuplicate = false;
$('.cat_entry').each(function() {
if(!$(this).text().indexOf(cat_input)) {
isDuplicate = true;
}
// And in the if else loop:
else if(isDuplicate == true)
//and just before the function ends
isDuplicate = false;
Thanks to all for the help you offered.

Categories