How Lodash findIndex Returns Element Position

The _.findIndex method in the Lodash JavaScript library searches an array and returns the zero-based index of the first element that satisfies a provided testing condition. This article explains the internal mechanics of _.findIndex, details how it evaluates different types of predicate arguments, and outlines how it handles return values when matching elements are found or absent.

Syntax and Parameters

The signature for the method is:

_.findIndex(array, [predicate=_.identity], [fromIndex=0])

Execution Flow

When invoked, _.findIndex executes sequentially through the target array starting at the specified fromIndex (or 0 by default):

  1. Iteration: It traverses elements in ascending order from left to right.
  2. Predicate Evaluation: For each element, Lodash applies the predicate to determine whether the condition is met.
  3. Early Exit on Match: As soon as the predicate returns a truthy value, the execution halts immediately, ignoring any remaining elements.
  4. Result: The function returns the numeric index of that first matching element. If the loop completes without any element satisfying the condition, it returns -1.

Predicate Types and Shorthands

Lodash provides multiple ways to define the predicate condition, converting shorthands into functions internally:

1. Custom Callback Function

You can pass a standard callback function that receives (value, index, collection). The method returns the index where this callback first returns a truthy value.

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const index = _.findIndex(users, user => user.name === 'Bob');
// Returns: 1

2. Object Matching (_.matches Shorthand)

Passing an object checks if an element contains matching key-value pairs.

const index = _.findIndex(users, { name: 'Charlie' });
// Returns: 2

3. Property and Value Array (_.matchesProperty Shorthand)

Passing a key-value pair as a two-element array checks for an exact match on that specific property.

const index = _.findIndex(users, ['id', 1]);
// Returns: 0

4. Property Name (_.property Shorthand)

Passing a string checks whether the property exists on the element and evaluates to a truthy value.

const items = [{ active: false }, { active: true }];
const index = _.findIndex(items, 'active');
// Returns: 1

Handling Starting Offsets

The optional third argument, fromIndex, changes the starting boundary of the search:

const numbers = [4, 6, 8, 10, 6, 12];

// Start searching from index 2
const index = _.findIndex(numbers, n => n === 6, 2);
// Returns: 4

Unmatched Elements

If no element satisfies the predicate, _.findIndex consistently returns -1. This behavior allows developers to quickly verify if an item exists by checking if the resulting index is greater than -1.