I’ve you’ve ever had to store some data for a simple, mostly-static website, the JavaScript filter function is extremely helpful.
Imagine an array of movie franchise objects like this:
var movieFranchises = [
{
id: 1,
name: "Star Wars",
rank: 1,
boxOffice: 4.2
},
{
id: 2,
name: "Harry Potter",
rank: 6,
boxOffice: 4.2
},
{
id: 3,
name: "Lord of the Rings",
rank: 2,
boxOffice: 1.86
}
];
What if you wanted to find the franchises with a rank in the Top 5 that also made more than $2 billion dollars?
Using filters, you could do something like this:
function filterMovies(m) {
return m.rank <= 5 && m.boxOffice >= 2;
}
var goodMovies = movieFranchises.filter(filterMovies);
console.log(goodMovies);
Voila! The goodMovies variable now stores an array of all the movies that meet the criteria.