Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Search and filter with optional criteria in JavaScript

82 Search and filter with every criterion optional

fair

Filter a list of vendors by any combination of a free-text query, one or more cities, a minimum rating and an active flag. Criteria that were not supplied must not narrow anything. Then write the version most people write first — the one that tests each criterion for truthiness — and show what it does when you ask for the inactive vendors.

Stuck? Three hints, smallest first
  1. 1. Build an array of predicate functions from the criteria that are present, then filter with every.
  2. 2. The test for "was this criterion supplied" is !== undefined, not truthiness.
  3. 3. [].concat(value) accepts one city or an array of them without a branch.

The answer

const vendors = [
  { id: 1, name: 'Adaeze Fabrics', city: 'Lagos', rating: 4.6, active: true },
  { id: 2, name: 'Balogun Textiles', city: 'Lagos', rating: 3.9, active: true },
  { id: 3, name: 'Chidi Electronics', city: 'Abuja', rating: 4.8, active: false },
  { id: 4, name: 'Ngozi Fabrics', city: 'Ibadan', rating: 4.2, active: true },
  { id: 5, name: 'Yaba Tech Spares', city: 'Lagos', rating: 2.7, active: false },
];

function search(rows, criteria = {}) {
  const tests = [];
  if (criteria.q !== undefined && criteria.q.trim() !== '') {
    const needle = criteria.q.trim().toLowerCase();
    tests.push((r) => r.name.toLowerCase().includes(needle));
  }
  if (criteria.city !== undefined) {
    const cities = [].concat(criteria.city);
    tests.push((r) => cities.includes(r.city));
  }
  if (criteria.minRating !== undefined) tests.push((r) => r.rating >= criteria.minRating);
  if (criteria.active !== undefined) tests.push((r) => r.active === criteria.active);
  return rows.filter((r) => tests.every((t) => t(r)));
}

// The version that checks truthiness instead of presence.
function naiveSearch(rows, criteria = {}) {
  return rows.filter((r) =>
    (!criteria.q || r.name.toLowerCase().includes(criteria.q.toLowerCase())) &&
    (!criteria.city || r.city === criteria.city) &&
    (!criteria.minRating || r.rating >= criteria.minRating) &&
    (!criteria.active || r.active === criteria.active));
}

const names = (rows) => rows.map((r) => r.name);

const everything = search(vendors);
const byText = search(vendors, { q: '  FABRICS ' });
const lagosOnly = search(vendors, { city: 'Lagos' });
const twoCriteria = search(vendors, { city: 'Lagos', minRating: 4 });
const severalCities = search(vendors, { city: ['Abuja', 'Ibadan'] });
const onlyInactive = search(vendors, { active: false });
const naiveInactive = naiveSearch(vendors, { active: false });
const floorOfZero = search(vendors, { minRating: 0 });
const blankQuery = search(vendors, { q: '   ' });
const noMatch = search(vendors, { city: 'Kano', q: 'fabrics' });

console.log('no criteria :', everything.length, 'rows');
console.log('q=fabrics   :', names(byText));
console.log('inactive    :', names(onlyInactive));
console.log('naive same  :', names(naiveInactive), '<- the bug');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('no criteria means no filtering', everything.length, 5);
test('the query is trimmed and case-insensitive', names(byText), ['Adaeze Fabrics', 'Ngozi Fabrics']);
test('a second criterion narrows: three Lagos vendors, one of them rated 4 or over', [lagosOnly.length, names(twoCriteria)], [3, ['Adaeze Fabrics']]);
test('city accepts one value or a list of them', names(severalCities), ['Chidi Electronics', 'Ngozi Fabrics']);
test('active: false really means inactive', names(onlyInactive), ['Chidi Electronics', 'Yaba Tech Spares']);
test('the truthiness version ignores it and returns everybody', naiveInactive.length, 5);
test('minRating: 0 is a real floor that happens to admit everyone', floorOfZero.length, 5);
test('a whitespace-only query is treated as no query', blankQuery.length, 5);
test('and criteria that match nothing give an empty list, not everything', noMatch, []);

The shape here — collect predicates, then rows.filter(r => tests.every(t => t(r))) — is worth keeping. Each criterion contributes one small function, the empty criteria object yields an empty tests array, and [].every(...) is true, so "no filters" falls out of the arithmetic instead of needing a special case.

The sixth assertion is the bug this exists to kill. !criteria.active is true when active is false, so the whole clause short-circuits away and the filter for inactive vendors returns every vendor. The same hole swallows minRating: 0, q: '' and page: 0. Any criterion whose valid values include a falsy one needs !== undefined, and active, 0 and '' are the three that turn up in real forms.

The one place truthiness is right is the blank query: a user who typed spaces into a search box supplied nothing, so q.trim() !== '' is a deliberate second condition rather than an oversight.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.