DEV Community

Cover image for Filter Arrays with complex searches made easy
Miguelángel Cabrera
Miguelángel Cabrera

Posted on • Edited on

Filter Arrays with complex searches made easy

The Filter Project

TLDR
@mcabreradev/filter filtering arrays is really easy.

This project provides a comprehensive implementation of a filter function in TypeScript. The filter function is a versatile tool that can be used to select a subset of items from an array based on a provided predicate function or expression.

The filter function in this project is designed to handle a wide variety of use cases. It can filter arrays of primitive values, objects, and even nested objects. The function also supports complex filtering expressions, including wildcard characters and regular expressions.

Whether you need to filter an array in a complex way, or you're just interested in understanding how a robust filter function can be implemented, this project is a valuable resource.

Installation

You can install this package using various package managers. Here are the commands for each of them:

npm

npm install @mcabreradev/filter
Enter fullscreen mode Exit fullscreen mode

Usage

After installation, you can import the filter function from the package like this:

import filter from '@mcabreradev/filter';
Enter fullscreen mode Exit fullscreen mode

If you're working in a Node.js environment, the installation process is the same as mentioned before. However, you can use the CommonJS syntax to import the filter function:

const filter = require('@mcabreradev/filter');
Enter fullscreen mode Exit fullscreen mode

Features

The filter function in the provided TypeScript code is a versatile function that allows you to select a subset of items from an array based on a variety of conditions. Here are some of its key features:

Array Filtering:

The primary purpose of the filter function is to filter an array. It takes an array and a predicate function as arguments, and returns a new array that includes only the items for which the predicate function returns true.

import filter from '@mcabreradev/filter';

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = filter(numbers, (n) => n % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Case-Insensitive Search:

The filter function supports case-insensitive search. When you provide a string as the predicate, it will match any property of the objects in the array that contains the string, regardless of case.

import filter from '@mcabreradev/filter';

const words = ['Apple', 'Banana', 'Cherry'];
const result = filter(words, 'a');

console.log(result); // Output: ['Apple', 'Banana']
Enter fullscreen mode Exit fullscreen mode

Wildcard Matching:

The filter function supports wildcard matching with the % and _ characters. The % character matches any sequence of characters, and the _ character matches any single character. These wildcards also work in a case-insensitive manner.

import filter from '@mcabreradev/filter';

const words = ['Apple', 'Banana', 'Cherry'];
const result = filter(words, 'A%e');

console.log(result); // Output: ['Apple']
Enter fullscreen mode Exit fullscreen mode

Multiple Conditions:

The filter function allows you to filter an array based on multiple conditions. You can specify these conditions as an object, where each key-value pair represents a condition that the items in the array must meet to be included in the result.

import filter from '@mcabreradev/filter';

const users = [
  { name: 'Alice', age: 20 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 30 },
];
const result = filter(users, { name: 'A%', age: 20 });

console.log(result); // Output: [{ name: 'Alice', age: 20 }]
Enter fullscreen mode Exit fullscreen mode

Custom Predicate Functions:

The filter function allows you to provide a custom predicate function to determine which items should be included in the result. This gives you maximum flexibility to define your own conditions for filtering the array.

import filter from '@mcabreradev/filter';

const numbers = [1, 2, 3, 4, 5];
const result = filter(numbers, (n) => n > 3);

console.log(result); // Output: [4, 5]
Enter fullscreen mode Exit fullscreen mode

Deep Comparison:

The filter function supports deep comparison of objects. This means that it can compare the properties of nested objects, not just the top-level properties.

import filter from '@mcabreradev/filter';

const users = [
  { name: 'Alice', age: 20, address: { city: 'New York' } },
  { name: 'Bob', age: 25, address: { city: 'Los Angeles' } },
  { name: 'Charlie', age: 30, address: { city: 'Chicago' } },
];
const result = filter(users, { address: { city: 'New York' } });

console.log(result); // Output: [{ name: 'Alice', age: 20, address: { city: 'New York' } }]
Enter fullscreen mode Exit fullscreen mode

Negation:

The filter function supports negation. If the predicate is a string that starts with !, the function will include an item in the result only if it does not match the rest of the string.

import filter from '@mcabreradev/filter';

const words = ['Apple', 'Banana', 'Cherry'];
const result = filter(words, '!Apple');

console.log(result); // Output: ['Banana', 'Cherry']
Enter fullscreen mode Exit fullscreen mode

Nested Objects:

The filter function can filter arrays with a nested object that has 2 node levels:

import filter from '@mcabreradev/filter';

const users = [
  { name: 'Alice', age: 20, address: { city: 'New York', country: 'USA' } },
  { name: 'Bob', age: 25, address: { city: 'Los Angeles', country: 'USA' } },
  { name: 'Charlie', age: 30, address: { city: 'London', country: 'UK' } },
];
const result = filter(users, { address: { country: 'USA' } });

console.log(result);

// Output:
//[
// { name: 'Alice', age: 20, address: { city: 'New York', country: 'USA' } },
// { name: 'Bob', age: 25, address: { city: 'Los Angeles', country: 'USA' } }
//]
Enter fullscreen mode Exit fullscreen mode

And here's an example of filter function with a nested object that has 3 node levels:

import filter from '@mcabreradev/filter';

const users = [
  {
    name: 'Alice',
    age: 20,
    address: {
      city: 'New York',
      country: 'USA',
      coordinates: { lat: 40.7128, long: 74.006 },
    },
  },
  {
    name: 'Bob',
    age: 25,
    address: {
      city: 'Los Angeles',
      country: 'USA',
      coordinates: { lat: 34.0522, long: 118.2437 },
    },
  },
  {
    name: 'Charlie',
    age: 30,
    address: {
      city: 'London',
      country: 'UK',
      coordinates: { lat: 51.5074, long: 0.1278 },
    },
  },
];

const result = filter(users, { address: { coordinates: { lat: 40.7128 } } });

console.log(result);

// Output:
// [{
//   name: 'Alice',
//   age: 20,
//   address: {
//       city: 'New York',
//       country: 'USA',
//       coordinates: {
//           lat: 40.7128,
//           long: 74.0060
//       }
//   }
// }]
Enter fullscreen mode Exit fullscreen mode

Advanced Examples of Use

The filter function can be used in a wide variety of scenarios. Here are some examples of how it can be used:

Filters customers with a specific city

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, 'Berlin');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers with a specific city with wildcard %

The % wildcard represents any number of characters, even zero characters.

return all customers that contains the pattern 'erlin':

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, '%erlin');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers that contains the pattern "Ber":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, 'Ber%');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers that contains the pattern "erli":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, '%erli%');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers with a specific city with wildcard _

The _ wildcard represents a single character. It can be any character or number, but each _ represents one, and only one, character.

return all customers with a City starting with any character, followed by "erlin":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, '_erlin');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City witch contains "erli":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, '_erli_');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City starting with "L", followed by any 2 characters, ending with "lin":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, 'B__lin');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers based on objects

return all customers with a City named "Berlin":

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: 'Berlin' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers based on object key value with wilcards %

return all customers with a City witch contains "erlin" at the end of the string:

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: '%erlin' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City witch contains "erli" at the begining of the string:

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: 'Berl%' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City witch contains "erlin" at the end of the string:

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: '_erlin' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City witch contains "erl" in the string:

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: '_erl__' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

return all customers with a City witch contains the characters "e,li" in the string:

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, { city: '_e_li_' });

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers based on a predicate function

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, ({ city }) => city === 'Berlin');

// Output:
// [{ name: 'Alfreds Futterkiste', city: 'Berlin' }]
Enter fullscreen mode Exit fullscreen mode

Filters customers based on based on two cities

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, ({ city }) => city === 'Berlin' || city === 'London');

// Output:
// [
//  { name: 'Alfreds Futterkiste', city: 'Berlin' },
//  { name: 'Around the Horn', city: 'London' },
//  { name: 'Bs Beverages', city: 'London' }
// ]
Enter fullscreen mode Exit fullscreen mode

Filters customers based on based on two cities if exists

import filter from '@mcabreradev/filter';

const customers = [
  { name: 'Alfreds Futterkiste', city: 'Berlin' },
  { name: 'Around the Horn', city: 'London' },
  { name: "B's Beverages", city: 'London' },
  { name: 'Bolido Comidas preparadas', city: 'Madrid' },
  { name: 'Bon app', city: 'Marseille' },
  { name: 'Bottom-Dollar Marketse', city: 'Tsawassen' },
  { name: 'Cactus Comidas para llevar', city: 'Buenos Aires' },
];

filter(customers, ({ city }) => city === 'Berlin' && city === 'Caracas');

// Output:
// []
Enter fullscreen mode Exit fullscreen mode

Looking for more?

You can take a look at my github repository https://github.com/mcabreradev/filter

Thanks..

Top comments (0)