如何在 Javascript 中过滤数组中的项目
2022-06-19
346
如何根据数组中的流派项过滤电影标题?
const result = [
{
title: "Mad Max: Fury Road",
genre: ["Action", "Adventure", "Sci-Fi"],
},
{
title: "The Hunger Games: Mockingjay Part 1",
genre: ["Adventure", "Thriller"],
},
{
title: "Jurassic World",
genre: ["Action", "Adventure", "Sci-Fi"],
},
{
title: "Everest",
genre: ["Drama", "Thriller"],
},
{
title: "Insurgent",
genre: ["Adventure"],
},
{
title: "Sicario",
genre: ["Action", "Crime", "Drama"],
},
];
假设我想根据流派过滤电影标题名称,例如:
“科幻”
,那么它应该返回电影标题数组,例如:
[“疯狂的麦克斯:狂暴之路”,“侏罗纪世界”]
。
尝试了各种映射和过滤器组合,但不起作用。
const newResult = result
.map((curr) => curr.genre.filter((ele) => ele === search))
.filter((ele) => ele);
3个回答
我们使用
filter
返回符合某些条件的所有电影。
对于
filter
的通过条件,我们在所提供的流派数组上使用
every
。
如果在调用它的数组 (
genreList
) 中的所有元素都针对某些条件返回 true,则
every
返回 true。
对于
every
的条件,我们检查电影的类型数组是否包含给定
genreList
数组中的条目。
因此,用英语来说,此代码表示“请给我所有具有在 gentleList 中给出的所有类型的电影”。
const result= [
{
"title": "Mad Max: Fury Road",
"genre": [
"Action",
"Adventure",
"Sci-Fi"
]
},
{
"title": "The Hunger Games: Mockingjay Part 1",
"genre": [
"Adventure",
"Thriller"
]
},
{
"title": "Jurassic World",
"genre": [
"Action",
"Adventure",
"Sci-Fi"
]
},
{
"title": "Everest",
"genre": [
"Drama",
"Thriller"
]
},
{
"title": "Insurgent",
"genre": [
"Adventure"
]
},
{
"title": "Sicario",
"genre": [
"Action",
"Crime",
"Drama"
]
}
];
const moviesByGenres = (moviesList, genreList) => {
return moviesList.filter((m) => {
return genreList.every((g) => m.genre.includes(g));
});
}
// All action movies
console.log(moviesByGenres(result, ["Action"]));
// All action+adventure movies
console.log(moviesByGenres(result, ["Action", "Adventure"]));
Swiffy
2022-06-19
使用
Array#filter
选择符合设定条件的相关项目,并使用
Array#map
选择您感兴趣的所选项目的属性。
const result= [ { "title": "Mad Max: Fury Road", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "The Hunger Games: Mockingjay Part 1", "genre": [ "Adventure", "Thriller" ] }, { "title": "Jurassic World", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "Everest", "genre": [ "Drama", "Thriller" ] }, { "title": "Insurgent", "genre": [ "Adventure" ] }, { "title": "Sicario", "genre": [ "Action", "Crime", "Drama" ] } ],
search = "Sci-Fi";
newResult = result
//which items meet the set criteria?
.filter(({genre}) => genre.includes(search))
//what about those items am I zeroing in on?
.map(({title}) => title);
console.log( newResult );
PeterKA
2022-06-19
经过反复试验找到了答案
const n = result.filter((curr) => curr['genre'].includes("Action"))
Jacob
2022-06-19