A search query often starts with a large collection and a simple question: which records satisfy this condition? Filtering answers by returning only the elements for which a predicate is true. In a book search, it keeps books whose titles include the query, before mapping the matches into result records. section 3.4
Searching books by title
function searchBooksByTitle(catalogData, query) { var allBooks = _.values(_.get(catalogData, "booksByIsbn")); var matchingBooks = _.filter(allBooks, function(book) { return _.get(book, "title").includes(query); }); return _.map(matchingBooks, function(book) { return bookInfo(catalogData, book); }); } With the query "Wat", the filter retains Watchmen, while the following map converts it into a result containing its title, ISBN, and author names. section 3.4
Listing 3.17 Custom implementation of filter
function filter(coll, f) {
var res = [];
for(var i = 0; i < coll.length; i++) { #1
if(f(coll[i])) {
res.push(coll[i]);
}
}
return res;
}
The essential implementation makes the control flow explicit: iterate through the collection, apply the predicate, and push passing elements into a result collection. section 3.4
The same idea can cross collection representations. An Immutable.js adaptation filters arrays directly and filters maps through their value sequence, allowing the search logic to retain the same shape while changing the data structure underneath. section 9.4.1
































