Home > Enterprise >  findindex return -1 Even though the array is not empty
findindex return -1 Even though the array is not empty

Time:08-21

I use the getMovie() function to get the data in the array through the id and at the "theatres" the data is returned to me correctly, but at the "trending or popular" it does not return any data and the index value is -1, although the array is not empty

export class MovieComponent implements OnInit {
  type = '';
  id = '';
  url = '';
  movies: any;
  movie: any;


  constructor(private route: ActivatedRoute, private http: HttpClient) {}

  ngOnInit(): void {
    this.type = this.route.snapshot.params['type'];
    this.id = this.route.snapshot.params['id'];
    if (this.type === 'Trending') {
      this.url = 'http://localhost:4200/assets/data/trending-movies.json';
    }
  else  if (this.type === 'Theatres') {
      this.url = 'http://localhost:4200/assets/data/theatre-movies.json';
    }
   else if (this.type === 'Popular') {
      this.url = 'http://localhost:4200/assets/data/popular-movies.json';
    }
    this.getMovie();
  }

  getMovie() {
    this.http.get(this.url).subscribe((movies) => {
      this.movies = movies;
      let index = this.movies.findIndex(
        (movie: { id: string }) => movie.id == this.id
      );
      console.log(index);
      if (index > -1) {
        this.movie = this.movies[index];
      }
    });
  }
}

CodePudding user response:

Here's the documentation on MDN.

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

Also, when working with typescript, you might want to actually type your members, instead of typing everything as any.

CodePudding user response:

It returns -1 because there aren't any elements that satisfy the testing function

CodePudding user response:

Try checking your searching terms, because as others have noted, -1 doesn't mean the array is not empty but rather no results came up with your searching term.

  • Related