I'm doing a search filter. I need to return the entire object containing the given actor by the user. I can find the actor, but I'm not sure how to return the object where the actor is.
JSON file:
{
"title": "American Assassin",
"year": 2017,
"cast": [
"Dylan O'Brien",
"Michael Keaton",
"Sanaa Lathan",
"Shiva Negar",
"Taylor Kitsch"
],
"genres": []
},
{
"title": "Mother!",
"year": 2017,
"cast": [
"Jennifer Lawrence",
"Javier Bardem",
"Michelle Pfeiffer",
"Domhnall Gleeson",
"Ed Harris",
"Kristen Wiig"
],
"genres": []
}
My filter function:
checkCast(allMovies) {
return filter(allMovies, (movie) => {
const actor = filter(movie.cast, (actor) => {
return actor.toLowerCase().includes(this.search.cast.toLowerCase())
})
console.log(actor)
return actor
});
}
Hope everything is clear.
CodePudding user response:
You need to filter the allMovies
array by looking for an actor in the case
array. Use Array.some()
(or lodash _.some()
) to return true
if a matching actor is found.
const search = { cast: 'bardem' };
function checkCast(allMovies) {
return allMovies.filter(movie =>
movie.cast.some(actor =>
actor.toLowerCase().includes(search.cast.toLowerCase())
)
);
}
const allMovies = [{"title":"American Assassin","year":2017,"cast":["Dylan O'Brien","Michael Keaton","Sanaa Lathan","Shiva Negar","Taylor Kitsch"],"genres":[]},{"title":"Mother!","year":2017,"cast":["Jennifer Lawrence","Javier Bardem","Michelle Pfeiffer","Domhnall Gleeson","Ed Harris","Kristen Wiig"],"genres":[]}]
const result = checkCast(allMovies)
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use array#find
with array#includes
to check if cast of movie include an actor.
const movies = [{ "title": "American Assassin", "year": 2017, "cast": [ "Dylan O'Brien", "Michael Keaton", "Sanaa Lathan", "Shiva Negar", "Taylor Kitsch" ], "genres": [] }, { "title": "Mother!", "year": 2017, "cast": [ "Jennifer Lawrence", "Javier Bardem", "Michelle Pfeiffer", "Domhnall Gleeson", "Ed Harris", "Kristen Wiig" ], "genres": [] }],
actor = 'Ed Harris',
movie = movies.find(({cast}) => cast.includes(actor));
console.log(movie);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
You can also do use convert actor and cast name to lower case to compare using array#find
and array#some
.
const movies = [{ "title": "American Assassin", "year": 2017, "cast": [ "Dylan O'Brien", "Michael Keaton", "Sanaa Lathan", "Shiva Negar", "Taylor Kitsch" ], "genres": [] }, { "title": "Mother!", "year": 2017, "cast": [ "Jennifer Lawrence", "Javier Bardem", "Michelle Pfeiffer", "Domhnall Gleeson", "Ed Harris", "Kristen Wiig" ], "genres": [] }],
actor = 'ed harris',
movie = movies.find(({cast}) => cast.some(member => member.toLowerCase() === actor.toLowerCase()));
console.log(movie);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>