Not able to compare strings in Javascript - javascript

I am trying to compare a string with a set of strings stored in an array. Here is the block of code:
then(op => {
if (op[0].probability > FILTER_THRESHOLD) {
if (FILTER_LIST.indexOf(op[0].className) > 1) {
console.log("EUREKA! EUREKA! EUREKA!")
console.log(op[0].className)
return true;
}
}
return false;
})
The second if statement should evaluate to true in some cases but it is not. The return is always false.
op[0].className should be a string and I am also able to get the value from op[0].probability correctly.
What could be the reason?
I have tried debugging and cannot seem to get why the 'if' statement is not being true.
Here is the FILTER_LIST array:
var FILTER_LIST = ["Hello", "Please", "Simple"];
Please advise how I can fix this!
Thank you!

indexOf(...) > 1 asks "did it find a match at the third element or later?" You'll get false if it matched at index 0 or 1. If you want just "it found one anywhere", you want !== -1, >= 0, or to use includes instead of indexOf.
if (FILTER_LIST.indexOf(op[0].className) !== -1) {
// or
if (FILTER_LIST.indexOf(op[0].className) >= 0) {
// or
if (FILTER_LIST.includes(op[0].className)) {

Related

javascript function always return the first element [duplicate]

This question already has answers here:
indexOf always returning true for document.location
(3 answers)
Closed 4 years ago.
I have the following javascript function to check a link and based on the link being a track or album, it should extract the id from the link, but it'll never go pass the first if statement, it will always alert found track in link, even though I provide a album link, any help would be appreciated.
the links look like the following :
https://open.spotify.com/album/1XGo0OD90wIlRccwLe29L9?si=egthfx9CRfuPIhLJ1uXCPA
https://open.spotify.com/track/1SWyGZhn3nyLUZRfWvQ0to?si=Tl-fwsqxQf-J8gZWps2PqQ
function getLinkID(link) {
if(link.indexOf("spotify")) {
if(link.indexOf("track")) {
alert("found track in link");
var linkID = link.split('track/').pop().split('?')[0];
} else if(link.indexOf("album")) {
alert("found album in link");
var linkID = link.split('album/').pop().split('?')[0];
}
} else if(link.indexOf("apple")) {
}
return linkID;
}
indexOf returns the index number of the match and if there is no match it return -1. Also, if there is a match at first index, then it will return 0 which is false which will break your code. You should use includes.
Update from
link.indexOf("spotify")
to
link.includes("spotify")
Note, includes will not work if you are using IE. For IE either you will need to create a polyfill or update the condition to link.indexOf("spotify") !== -1
function always return the first element
The problem here is that the first condition will be always true, only if the index is 0, even if the word doesn't appear in the link, because link.indexOf("spotify") will return an index or -1.
So when the word isn't not found it will return -1 which is a truthy value, that's why the condition will be true, you can confirm this by typing Boolean(-1) in the console.
You need to check that the returned index is higher than -1, so the condition can be evaluated correctly:
if(link.indexOf("spotify")>-1)
IndexOf returns -1 if it’s not found and -1 is a truth value. Therefore it will always return true.
Try this :)
function getLinkID(link) {
if (link.indexOf("spotify") > -1) {
if (link.indexOf("track") > -1) {
alert("found track in link");
var linkID = link.split('track/').pop().split('?')[0];
} else if(link.indexOf("album") > -1) {
alert("found album in link");
var linkID = link.split('album/').pop().split('?')[0];
}
} else if(link.indexOf("apple") > -1) {
}
return linkID;
}

Angular 2 ng-class depending on function

Im trying to change the class of some elements based on an array.
I have declared a function to return a boolean and say if the string(state/class) is contained in the array.
I have call it isState(st: string) {return (this.ArrayWithClasses.indexOf(st) > 0)}
And then I do
[ngClass]="{'class-I-Want-To-Activate': isState('evaluating-this-state') }"
But it is´t working. You see my mistake? A best solution?
Edit: It is working if I use just a boolean to toggle the class. So I consider if function is what is wrong...
You shouldn't check if indexOf() value is > 0, because, if that string is located on the first place in array, you will get 0.
isState(st: string) {
let temp = this.ArrayWithClasses.indexOf(st);
if(temp != -1)
return true;
else
return false;
}
If searched string is not located in the array , you will get -1 value for that.
Use the below
isState(st: string) {
let temp=this.ArrayWithClasses.indexOf(st)
if(temp)
return true;
else
return false;
}

Javascript: For Loop, need help understanding this exercise with if/else

I have this exercise that already got the answer, but after hearing the explanations, still don't understand. This is the exercise:
"write a function isUniform() which takes an array as an argument and
returns true if all elements in the array are identical"
This is the solution
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
}
return true;
}
I got it almost right, but i did a else statement with the "return true" and it didn't work. Why does it work with the "return true" outside of the for loop?
(edited) This is how i did the first time:
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
else {
return true;
}
}
}
If you return true outside the loop, then it checks every element in the loop until one matches the if test or it gets to the end of the loop.
If you return true inside the loop then it will always hit a return statement for the first element and then stop the loop.
I got it almost right, but i did a else statement with the "return
true" and it didn't work
The solution below would return the wrong results in some cases because all it does is find the first element within the array that's equal to first variable and return true, even though it hasn't searched the entire array.
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
else {
return true;
}
}
}
I have this exercise that already got the answer, but after hearing
the explanations, still don't understand.
let's assume this is your array:
[10,10,13,10,10]
let's assume this is the variable first:
first = 10;
The if statement below which is within the for loop basically says if the variable first ( 10 ) is not equal to the element at the current index i (nth number within the array) then return false. This makes sense because if at this moment the variable first is not the same with the element at the specified index for example index 2 (number 13) then there is no point to carry on. Hence, it will return false.
if (numArr[i] !== first) {
return false;
}
now let's assume the array is:
[10,10,10,10,10]
let's assume this is the variable first:
first = 10;
now the variable first will be compared against each elementwithin the array and it says "is 10 not equal to the current element". in this case that's false because 10 is equal to 10. This will propagate down the array and control will never pass inside the if block. Eventually, control passes down to the return true statement.
if (numArr[i] !== first) {
return false;
}
It works because is the final statement in your function. Basically your function will return true if the condition inside for loop will not be triggered
Let's say you've got a broken printer which once in a while messes the printout. Now you printed 20 copies and want to know if every paper is fine. So now you would have to iteratively compare every copy until you found one which is not matching (and know it's time to get a new printer?). Or you've gone the way through the hole stack and know every copy is fine (and you've wasted time for nothing).

javascript conditional not reaching else

I'm working on creating a toggle function to 'favorite' an item from a list of many. I've got working script to toggle the item in and out of a user-specific favorites list, communicate that change to a database, and populate the rest of the site accordingly. That all works fine, it's mostly PHP and Ajax.
However, my javascript is ass. I'm stuck on a conditional to change the icon from a filled heart to an empty one. For some reason it never reaches the else statement even when the if statement is false. If I reverse the conditions, it still handles the if fine but never the else.
the image is:
<img src="includes/icons/fave-<?php echo $favStatus; ?>.png" id="faveToggle" class="faveIcon" onClick="toggleFave()">
the conditional, located in toggleFave() is:
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")){
document.getElementById('faveToggle').src = "includes/icons/fave-true.png";
} else {
document.getElementById('faveToggle').src = "includes/icons/fave-false.png";
}
So, uhh, whuddo I do?
indexOf returns the 0-based index of where the substring is found, or -1 if not. -1 happens to be "truthy".
That means you have two possibilities, it's either in the string and has a positive (truthy) position, or it's not and you get a truthy -1. Either way, it will always go into the first block. You want:
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png") > 0){
You only need to fetch the element once:
var toggle = document.getElementById("faveToggle");
if (toggle.src.indexOf("fave-false.png") >= 0) {
toggle.src = "includes/icons/fave-true.png";
}
else {
toggle.src = "includes/icons/fave-false.png";
}
The .indexOf() function returns the position of the searched-for substring, or -1 if it isn't found.
You can checkif it is greater than -1
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")>-1){
alert('1')
document.getElementById('faveToggle').src = "includes/icons/fave-true.png";
} else {
alert("2")
document.getElementById('faveToggle').src = "includes/icons/fave-false.png";
}
jsfiddle
Here's my simplified version using a ternary operator:
var toggle = document.getElementById('faveToggle'),
newState = toggle.src.toString().indexOf("fave-false.png") == -1 ? true : false;
toggle.src = "includes/icons/fave-"+newState+".png";
You can use the bitwise not ~ operator for checking.
~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:
value ~value boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on
if(~document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")){

How to use IndexOf in JQuery

if($('#this').val().indexOf('4289')){
Do something
else
Do something.
This works only with that 4289,
When I try to add other numbers to be indexed next to it using 'or', it doesn't work. How should I put other number. E.g
IndexOf('4289||78843')
I want this to check this numbers and if the number in the input field is not one of this, to echo error.
Here's more which happens to die when one revisits the field.
$('#Zip').blur(function(){
if (($(this).val().indexOf('0860') > -1)||($(this).val().indexOf('0850') > -1)){
$('#Status_Zip').html("No way.")
$(this).alterClass('*_*', 'Success')
return false;
}else{$('#Status_Code').hide()
$(this).alterClass('*_*', 'Error')
$(this).css('border-color', '#F00').css('background-color', '#FFC').effect("pulsate",{times:4},2)
return true;
}
})
That's because it would be looking for the string '4289||78843', which doesn't exist in the target I'm assuming. Logical operators can't just be tossed in anywhere, only where there are actual values to logically operate on. Something like this:
if(($('#this').val().indexOf('4289') > -1) ||
($('#this').val().indexOf('78843') > -1))
The return value of the indexOf() function is the numeric index of that value in the target value, or -1 if it's not found. So for each value that you're looking for, you'd want to check if it's index is > -1 (which means it's found in the string). Take that whole condition and || it with another condition, and that's a logical operation.
Edit: Regarding your comment, if you want to abstract this into something a little cleaner and more generic you might extract it into its own function which iterates over a collection of strings and returns true if any of them are in the target string. Maybe something like this:
function isAnyValueIn(target, values) {
for (var i = 0; i < values.length; i++) {
if (target.indexOf(values[i]) > -1) {
return true;
}
}
return false;
}
There may even be a more elegant way to do that with .forEach() on the array, but this at least demonstrates the idea. Then elsewhere in the code you'd build the array of values and call the function:
var values = ['4289', '78843'];
var target = $('#this').val();
if (isAnyValueIn(target, values)) {
// At least one value is in the target string
}

Categories