0

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!

3
  • The classnames are "Hello" "Please" and "Simple". Commented Jul 9, 2020 at 18:15
  • So they should match perfectly right? Or am I missing something? Commented Jul 9, 2020 at 18:15
  • Take a look at the answer below as to why your if logic is flawed. Commented Jul 9, 2020 at 18:16

1 Answer 1

2

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)) {
Sign up to request clarification or add additional context in comments.

5 Comments

Let me check that
It did not work as expected. The logic is correct but for some reason it is still returning false. What could be the reason??
@NavenduPottekkat - Your best bet here is to put a breakpoint on the line and look closely at the array and at the string you're checking. Alternatively, please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button; here's how to do one). My guess is className has another class in it, or a space at the beginning, or at the end, etc., etc.
The problem is I have to build this code. i.e I use parcel to build this js file and that file is run in the browser. In that case, how would I be able to debug?
@NavenduPottekkat - Use the debugger built into the browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.