0
var movies = [{  
     title: "Mission Impossible 2",
     year: 2000,
     rating: 5,
     genre: ["Action"]
}, {
    title: "The Mummy",
    year: 1999,
    rating: 6,
    genre: ["Action", "Comedy"]
}]

var list = "Action"
console.log(movies.filter(function (movie) {
    return isInSet(list, movie);
}))

console.log(movies.filter(isInSet.bind(null, list)))

function isInSet(set, item) {
    return set.indexOf(item.genre) > -1;
}

This returns with mission impossible

Now what I would like to do is change list to

var list = ["Action", "Comedy"]

but when I do it returns with an empty array, Can anyone help explain how to search the array of genre with the array list; to return The Mummy?

Thanks in advance

4
  • Should it only return results containing all specified genres or atleast 1? Commented Feb 14, 2018 at 21:46
  • Possible duplicate of How to filter array with array condition Commented Feb 14, 2018 at 21:49
  • @ManuelOtto Should contain all specified genres Commented Feb 15, 2018 at 23:43
  • @fubar Not completely duplicated, I need a .bind function Commented Feb 15, 2018 at 23:44

2 Answers 2

0

Assuming that you require every genre in the list to be included in the genres of a movie for a match, you can use a combination of the array .filter, .every, and .includes methods to get a list of matching items:

var movies = [{  
     title: "Mission Impossible 2",
     year: 2000,
     rating: 5,
     genre: ["Action"]
}, {
    title: "The Mummy",
    year: 1999,
    rating: 6,
    genre: ["Action", "Comedy"]
}]

var list = ["Action", "Comedy"]

console.log(movies.filter(movie => list.every(item => movie.genre.includes(item))))

Sign up to request clarification or add additional context in comments.

4 Comments

Is there anyway to do this keeping the .bind? (for homework)
movies.filter(movie => list.every(isInSet.bind(null, list))) should work. Or do you need to get rid of all the arrow functions completely?
Would probably be better to get rid of them all together but if that's asking too much don't worry about it, thank you btw
Edit: I just tried using the .bind line and it seems to be giving me an empty array again
0

Compare all the items in the search criteria against the genre of each movie, and return true if all were found.

This can be done with .every().

var movies = [{  
     title: "Mission Impossible 2",
     year: 2000,
     rating: 5,
     genre: ["Action"]
}, {
    title: "The Mummy",
    year: 1999,
    rating: 6,
    genre: ["Action", "Comedy"]
}];

var data = ["Action", "Comedy"];

var result = movies.filter(m =>
    data.every(s => m.genre.includes(s))
);

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.