or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Lodash Matches

Lodash matches is a utility function that creates a predicate function for deep object comparison. It takes a source object as input and returns a function that tests whether other objects contain all the key-value pairs present in the source object, using deep equality comparison.

Package Information

  • Package Name: lodash
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash
  • Specific Function: matches (from lodash v3.1.0)

Core Imports

CommonJS (primary method for v3.1.0):

const _ = require("lodash");
const matches = _.matches;

Global usage (browser):

const matches = _.matches;

AMD usage:

define(['lodash'], function(_) {
  const matches = _.matches;
});

Basic Usage

const _ = require("lodash");

// Create sample data
const users = [
  { user: 'fred', age: 40 },
  { user: 'barney', age: 36 }
];

// Create a matcher function
const matchesAge = _.matches({ age: 36 });

// Use with collection methods
const result = _.filter(users, matchesAge);
// => [{ user: 'barney', age: 36 }]

const found = _.find(users, matchesAge);
// => { user: 'barney', age: 36 }

Capabilities

Matches Function

Creates a function that performs deep comparison between objects and the provided source pattern.

/**
 * Creates a function which performs a deep comparison between a given object
 * and `source`, returning `true` if the given object has equivalent property
 * values, else `false`.
 * 
 * @static
 * @memberOf _
 * @category Utility
 * @param {Object} source - The object of property values to match
 * @returns {Function} Returns the new predicate function
 */
function matches(source);

The returned predicate function signature:

/**
 * @param {Object} object - The object to inspect
 * @returns {boolean} Returns `true` if object matches, else `false`
 */
function predicate(object);

Usage Examples:

const _ = require("lodash");

// Simple property matching
const matchName = _.matches({ name: 'fred' });
matchName({ name: 'fred', age: 40 }); // => true
matchName({ name: 'barney', age: 36 }); // => false

// Multiple property matching
const matchMultiple = _.matches({ age: 36, active: true });
matchMultiple({ name: 'barney', age: 36, active: true }); // => true
matchMultiple({ name: 'fred', age: 40, active: true }); // => false

// Deep object matching
const user = {
  profile: { 
    name: 'fred',
    settings: { theme: 'dark' }
  },
  status: 'active'
};

const matchNested = _.matches({ 
  profile: { 
    settings: { theme: 'dark' } 
  } 
});
matchNested(user); // => true

// Array and mixed type matching
const matchComplex = _.matches({
  tags: ['javascript', 'lodash'],
  metadata: { version: 1 }
});

matchComplex({
  name: 'project',
  tags: ['javascript', 'lodash'],
  metadata: { version: 1, created: '2023-01-01' }
}); // => true

Key Characteristics

  • Deep Comparison: Performs recursive equality checks on nested objects and arrays
  • Partial Matching: Only requires that the target object contains all properties from the source (additional properties in target are ignored)
  • SameValueZero Equality: Uses SameValueZero comparison algorithm (like ===, but NaN equals NaN)
  • Immutable Source: The source object is deep cloned internally, so modifications to the original source don't affect the matcher
  • Type Flexibility: Works with primitives, objects, arrays, and mixed data structures

Common Use Cases

const _ = require("lodash");

const products = [
  { name: 'laptop', category: 'electronics', price: 999, inStock: true },
  { name: 'book', category: 'media', price: 29, inStock: false },
  { name: 'phone', category: 'electronics', price: 599, inStock: true }
];

// Filter by category
const electronics = _.filter(products, _.matches({ category: 'electronics' }));

// Find available electronics
const availableElectronics = _.filter(products, _.matches({ 
  category: 'electronics', 
  inStock: true 
}));

// Check if any products match criteria
const hasAffordableElectronics = _.some(products, _.matches({ 
  category: 'electronics',
  price: 599
}));

// Use with array methods
const matchElectronics = _.matches({ category: 'electronics' });
const electronicsArray = products.filter(matchElectronics);

Edge Cases and Behavior

const _ = require("lodash");

// Empty source object matches everything
const matchAll = _.matches({});
matchAll({ anything: 'here' }); // => true
matchAll({}); // => true

// NaN handling (SameValueZero comparison)
const matchNaN = _.matches({ value: NaN });
matchNaN({ value: NaN }); // => true (unlike === comparison)

// Null and undefined handling
const matchNull = _.matches({ value: null });
matchNull({ value: null }); // => true
matchNull({ value: undefined }); // => false
matchNull({}); // => false (missing property)

// Array matching requires exact order and values
const matchArray = _.matches({ items: [1, 2, 3] });
matchArray({ items: [1, 2, 3] }); // => true
matchArray({ items: [3, 2, 1] }); // => false (different order)
matchArray({ items: [1, 2, 3, 4] }); // => false (different length)

// Empty arrays and objects in source match any arrays/objects in target
const matchEmpty = _.matches({ items: [], config: {} });
matchEmpty({ items: [1, 2, 3], config: { theme: 'dark' } }); // => true
matchEmpty({ items: [], config: {} }); // => true

// Deep nested object matching
const matchDeep = _.matches({
  user: {
    profile: {
      settings: { notifications: true }
    }
  }
});

matchDeep({
  user: {
    name: 'alice',
    profile: {
      age: 30,
      settings: { 
        notifications: true,
        theme: 'dark'
      }
    }
  }
}); // => true (contains required nested structure)

Error Handling

The matches function itself does not throw errors under normal usage. The returned predicate function handles:

  • Null/undefined objects: Returns false when the object to test is null or undefined
  • Missing properties: Returns false when required properties are missing
  • Type mismatches: Returns false when property values don't match using SameValueZero comparison
const _ = require("lodash");

const matcher = _.matches({ name: 'fred' });

matcher(null); // => false
matcher(undefined); // => false
matcher({}); // => false (missing name property)
matcher({ name: 'fred' }); // => true

Related Functions

While this K-tile focuses on _.matches, Lodash v3.1.0 includes related functions that work with similar matching logic:

  • _.where(collection, source): Filters a collection using the same deep comparison logic as matches
  • _.isMatch(object, source): Performs direct object comparison without creating a predicate function
  • _.findWhere(collection, source): Finds the first element that matches the source object

These functions use the same underlying matching algorithm and complement _.matches in collection operations.