UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

31 lines (30 loc) 1.4 kB
const require_iteratee = require("../util/iteratee.js"); const require_toInteger = require("../util/toInteger.js"); const require_identity = require("../function/identity.js"); //#region src/compat/array/findIndex.ts /** * Finds the index of the first item in an array that has a specific property, where the property name is provided as a PropertyKey. * * @template T * @param arr - The array to search through. * @param doesMatch - The criteria to match against the items in the array. This can be a function, a partial object, a key-value pair, or a property name. * @param [fromIndex=0] - The index to start the search from, defaults to 0. * @returns The index of the first item that has the specified property, or `-1` if no match is found. * * @example * // Using a property name * const items = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]; * const result = findIndex(items, 'name'); * console.log(result); // 0 */ function findIndex(arr, doesMatch = require_identity.identity, fromIndex = 0) { if (!arr) return -1; fromIndex = require_toInteger.toInteger(fromIndex); if (fromIndex < 0) fromIndex = Math.max(arr.length + fromIndex, 0); const subArray = Array.from(arr).slice(fromIndex); const iteratee$1 = require_iteratee.iteratee(doesMatch); const index = subArray.findIndex(iteratee$1); return index === -1 ? -1 : index + fromIndex; } //#endregion exports.findIndex = findIndex;