Filter rows with MongoDB-style operators, paths, and $or
An admin dashboard lets support staff save filters such as “active customers in the US or Canada with at least 3 orders”. The filters are stored as small query objects, in a style similar to MongoDB. Implement filterRows(rows, query), which returns the rows that match a query.
filterRows(rows, query) // => matching rows
query is either a field path or a logical operator ($or, $and). A row matches when every key matches. An empty query {} matches every row.'address.city' reads row.address.city. If any step is missing or is not an object, the field value is undefined.null): the field must be strictly equal (===) to it, or| Operator | Matches when the field value v … |
|---|---|
$eq / $ne |
v === x / v !== x |
$gt, $gte, $lt, $lte |
compares with >, >=, <, <=, but only when v and x are both numbers or both strings. Otherwise it does not match. |
$in / $nin |
is === to some element of the array x / to none of them |
$exists |
is not undefined when x is true; is undefined when x is false |
$contains |
is an array with an element === x, or a string that contains the string x |
$or: [q1, q2, ...] matches when at least one sub-query matches. $or: [] matches nothing.$and: [q1, q2, ...] matches when every sub-query matches. $and: [] matches everything.$ (as a query key or inside an operator object), and any key in an operator object that is not an operator, is an unknown operator. Check the whole query before filtering and throw an Error whose message contains that key, even if rows is empty.rows or query.const customers = [
{ id: 1, name: 'Ada', country: 'US', orders: 5, tags: ['vip'], address: { city: 'Austin' } },
{ id: 2, name: 'Bo', country: 'CA', orders: 1, tags: [], address: { city: 'Toronto' } },
{ id: 3, name: 'Chen', country: 'FR', orders: 8, tags: ['beta'] },
{ id: 4, name: 'Dee', country: 'US', orders: 3, tags: ['vip', 'beta'], address: { city: 'Boston' } },
];
filterRows(customers, { country: { $in: ['US', 'CA'] }, orders: { $gte: 3 } });
// => rows 1 and 4
filterRows(customers, { 'address.city': { $exists: false } });
// => row 3
filterRows(customers, { $or: [{ tags: { $contains: 'beta' } }, { orders: { $lt: 2 } }] });
// => rows 2, 3 and 4
filterRows(customers, { name: { $startsWith: 'A' } });
// throws Error: Unknown operator: $startsWith