我试图完成一项挑战,但我陷入了困境:
我有一个大电影数组,它的内部genreName是另一个数组。我想通过对照存储在selectedGenres数组中的复选框的选定流派检查其流派名称来过滤这部电影
当我不得不针对selectedGenres中的所有元素检查每个genreName数组时,我的困难就出现在这里。任务是,如果selectedGenre中有多个流派,以仅显示具有所有选定流派的电影,而不仅仅是其中一个。

码:

const movies = [
{title:"movie 1",genreName:["Action", "Drama"]},
{title:"movie 2",genreName:["Action", "Fantasy", "Adventure"]},
{title:"movie 3",genreName:["Action", "Fantasy", "Science Fiction"]},
{title:"movie 4",genreName:["Action", "Drama", "Thriller"]}
]
const selectedGenres = ["Action","Drama"];  //based on this selection, only movie1 and movie4 should be in the filteredMovies variable.

const filteredMovies = movies.filter(movie => { //loop through each movie
        movie.genreName.filter(genre => { // loop through each item in genreName array
          return selectedGenres.forEach(name => { // loop through each item in selectedGenres array
            return name.indexOf(genre) > -1;
          });
        });
      });

最佳答案

在电影上使用filter,对于选择了true类型的电影返回every



const movies = [
{title:"movie 1",genreName:["Action", "Drama"]},
{title:"movie 2",genreName:["Action", "Fantasy", "Adventure"]},
{title:"movie 3",genreName:["Action", "Fantasy", "Science Fiction"]},
{title:"movie 4",genreName:["Action", "Drama", "Thriller"]}
]
const selectedGenres = ["Action","Drama"];  //based on this selection, only movie1 and movie4 should be in the filteredMovies variable.


const filteredMovies = movies.filter(movie => selectedGenres.every(filter => movie.genreName.includes(filter)))

console.log(filteredMovies);

09-25 17:15