Skip to content
VersionSize

findIndex

The findIndex utility returns the index of the first element in an array that passes the provided test function. If no element matches, it returns -1.

Implementation

View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
import type { Predicate } from '../types';

/**
 * Finds the first element in an array that satisfies a predicate function. If no such element is found, returns -1.
 *
 * @example
 * ```ts
 * const arr = [1, 2, 3, 4, 5];
 * const isEven = (num) => num % 2 === 0;
 * findIndex(arr, isEven); // 1
 * findIndex(arr, (num) => num > 5); // -1
 * ```
 *
 * @param array - The array to search.
 * @param predicate - A function that is called for each element in the array.
 *
 * @return The index of the first element that satisfies the predicate, or -1 if no such element is found.
 */
export function findIndex<T>(array: T[], predicate: Predicate<T>) {
  assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });

  for (let index = 0; index < array.length; index++) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }

  return -1;
}

findIndex.fp = true;

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Short-circuiting: Stops searching as soon as the first match is found.
  • Type-safe: Properly typed predicate support.

API

ts
function findIndex<T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): number;

Parameters

  • array: The array to search.
  • predicate: The function to test each element. It receives:
    • item: The current element.
    • index: The index of the current element.
    • array: The original array.

Returns

  • The zero-based index of the first matching element, or -1 if no match is found.

Examples

Finding an Index

ts
import { findIndex } from '@vielzeug/toolkit';

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Find index of 'cherry'
findIndex(fruits, (f) => f === 'cherry'); // 2

// Find index of a fruit starting with 'z'
findIndex(fruits, (f) => f.startsWith('z')); // -1

Finding Object Index

ts
import { findIndex } from '@vielzeug/toolkit';

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

const bobIndex = findIndex(users, (u) => u.name === 'Bob'); // 1

Implementation Notes

  • Throws TypeError if the first argument is not an array.
  • Stops iterating as soon as the predicate returns truthy.
  • Does not modify the original array.

See Also

  • find: Get the first matching element itself.
  • findLast: Get the last matching element.
  • search: Find elements based on a query.