liveBook · Manning

Filtering

As explained in Data-Oriented Programming: Reduce software complexity

A filter function returns the elements of a collection that satisfy a specified predicate.

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

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains the predicate-driven loop and adapts filtering across arrays and maps, without descending into library implementation internals.
Examples
Demonstrates title matching with Watchmen, a custom filter implementation, and equivalent filtering in Immutable.js.
What it assumes
Assumes collections, predicates, records, and basic map operations while teaching filtering implementation through a simple loop.
What you can do after
Apply it via Lodash or Immutable.js, or build it from scratch with a predicate-driven loop.
How it connects
Connects filtering with predicates, map, Lodash, Immutable.js, persistent data structures, and search queries.

Also explained in

Compare how 33 books explain filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.