0

I am trying to loop out a list of names and console.logging the values that match. Am I going wrong using (if value in array)?

    for (var i = 0; i < this.state.apiResponse.length ; i++) {

      var selectedChars = this.state.chosenChars
      var returnedChars = this.state.apiResponse[i].name

      console.log(selectedChars)
      console.log(returnedChars)


      // I think i'm making a mistake with this if statement
      if (returnedChars in selectedChars) {
        console.log(this.state.apiResponse[i].name);            
      }

The selectedChars array and returned values:

["Luke Skywalker", "Han Solo"]

Luke Skywalker
Han Solo
Chewbacca

3 Answers3

0

Don't use in operator. Instead use indexOf:

for (var i = 0; i < this.state.apiResponse.length ; i++) {

  var selectedChars = this.state.chosenChars
  var returnedChars = this.state.apiResponse[i].name

  console.log(selectedChars)
  console.log(returnedChars)


  // I think i'm making a mistake with this if statement
  if (selectedChars.indexOf(returnedChars)!==-1) {
    console.log(this.state.apiResponse[i].name);            
  }
optimus
  • 834
  • 1
  • 10
  • 22
0

You have to use string.indexOf(substring):

if (selectedChars.indexOf(returnedChars) !== -1) {
  console.log(this.state.apiResponse[i].name);            
}

string.indexOf(substring) returns the index of the substring in the string, or -1 if the substring can't be found. If we check for "anything except -1", we can make sure the returnedChars are in the selectedChars.

Daniel Diekmeier
  • 3,401
  • 18
  • 33
  • ah, I had tried using (selectedChars.indexOf(returnedChars)). I wasn't checking it against the !==-1, thanks for clarifying this! –  May 10 '16 at 21:05
0

Yeah, it is not python, it's javascript :)

You can use indexOf() method on arrays.

  if (selectedChars.indexOf(returnedChars) > -1) {
    console.log(this.state.apiResponse[i].name);            
  }

Sorry,, search() is for strings.

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60