diff --git a/src/compat/array/lastIndexOf.spec.ts b/src/compat/array/lastIndexOf.spec.ts index 70054ef21..c246f5bc3 100644 --- a/src/compat/array/lastIndexOf.spec.ts +++ b/src/compat/array/lastIndexOf.spec.ts @@ -13,6 +13,10 @@ describe('lastIndexOf', () => { expect(lastIndexOf(array, 3)).toBe(5); }); + it(`should work with \`NaN\``, () => { + expect(lastIndexOf([1, 2, 3, NaN, 1, 2], NaN)).toBe(3); + }); + it(`should work with a positive \`fromIndex\``, () => { expect(lastIndexOf(array, 1, 2)).toBe(0); }); diff --git a/src/compat/array/lastIndexOf.ts b/src/compat/array/lastIndexOf.ts index 28d9294d9..496a7453e 100644 --- a/src/compat/array/lastIndexOf.ts +++ b/src/compat/array/lastIndexOf.ts @@ -1,5 +1,22 @@ import { isArrayLike } from '../predicate/isArrayLike'; +/** + * Finds the index of the last occurrence of a value in an array. + * + * This method is similar to `Array.prototype.lastIndexOf`, but it also finds `NaN` values. + * It uses strict equality (`===`) to compare elements. + * + * @template T - The type of elements in the array. + * @param {ArrayLike | null | undefined} array - The array to search. + * @param {T} searchElement - The value to search for. + * @param {number} [fromIndex] - The index to start the search at. + * @returns {number} The index (zero-based) of the last occurrence of the value in the array, or `-1` if the value is not found. + * + * @example + * const array = [1, 2, 3, NaN, 1]; + * lastIndexOf(array, 3); // => 4 + * lastIndexOf(array, NaN); // => 3 + */ export function lastIndexOf(array: ArrayLike | null | undefined, searchElement: T, fromIndex?: number): number { if (!isArrayLike(array) || array.length === 0) { return -1; @@ -12,5 +29,14 @@ export function lastIndexOf(array: ArrayLike | null | undefined, searchEle index = index < 0 ? Math.max(length + index, 0) : Math.min(index, length - 1); } + // `Array.prototype.lastIndexOf` doesn't find `NaN` values, so we need to handle that case separately. + if (Number.isNaN(searchElement)) { + for (let i = index; i >= 0; i--) { + if (Number.isNaN(array[i])) { + return i; + } + } + } + return Array.from(array).lastIndexOf(searchElement, index); }