how to use the matches function from the underscore library in javascript

The _.matches function from the Underscore library in JavaScript allows you to create a predicate function for filtering objects that match a specific set of key-value pairs. The function takes an object as an argument and returns a boolean value indicating whether the object matches the specified key-value pairs.

Here is an example of how to use _.matches to filter an array of objects based on a certain key-value pair:

index.tsx
const array = [{name: 'John', age: 25}, {name: 'Mary', age: 30}, {name: 'Bob', age: 25}];
const matcher = _.matches({age: 25});

const filteredArray = _.filter(array, matcher);
console.log(filteredArray); // [{name: 'John', age: 25}, {name: 'Bob', age: 25}]
258 chars
6 lines

In this example, we create an array of objects representing people, and we want to filter this array to only include people who are 25 years old. We first create a matcher function using _.matches({age: 25}). This function will return true for any object that has an age key with a value of 25.

We then use the _.filter function from Underscore to apply this matcher function to each object in the original array, returning a new array with only the objects that match our criteria.

Note that _.matches is also capable of using regular expressions to match values, as shown in the following example:

index.tsx
const array = [{name: 'John', age: 25}, {name: 'Mary', age: 30}, {name: 'Bob', age: 25}];
const matcher = _.matches({name: /Jo.*/});

const filteredArray = _.filter(array, matcher);
console.log(filteredArray); // [{name: 'John', age: 25}]
239 chars
6 lines

In this example, we filter the array to only include objects whose name key starts with "Jo". We achieve this by using a regular expression in the matcher object.

gistlibby LogSnag