Finding NaN in Float Arrays with Lodash findIndex
When searching for NaN inside an array of floating-point
numbers using Lodash's _.findIndex, the return value
depends entirely on how the search criteria is passed. If
NaN is passed directly as the second argument
(_.findIndex(array, NaN)), the method returns
-1 because NaN is not treated as an equality
target. However, if a valid predicate function such as
_.isNaN or Number.isNaN is provided,
_.findIndex returns the zero-based index of the first
NaN float in the array, or -1 if no
NaN is present.
Passing NaN Directly as a Predicate
If you attempt to find NaN by passing the literal value
directly:
const floats = [1.25, 4.5, NaN, 8.75];
const result = _.findIndex(floats, NaN); // Returns: -1The method returns -1 even though NaN
exists at index 2.
This occurs because _.findIndex expects a predicate
function. When passed a primitive value that is neither a function, an
object, nor an array shorthand, Lodash invokes
_.property(NaN). This evaluates each element by accessing
the property key NaN on the number primitive (effectively
checking floatElement[NaN]). Because numbers in JavaScript
do not possess a NaN property, this check evaluates to
undefined (falsy) for every element in the array, causing
the search to fail and return -1.
Using a Predicate Function to Find NaN
To accurately locate NaN using _.findIndex,
you must provide a predicate function capable of evaluating
NaN values:
const floats = [1.25, 4.5, NaN, 8.75];
const result = _.findIndex(floats, _.isNaN); // Returns: 2You can use Lodash's built-in _.isNaN or standard
JavaScript's Number.isNaN:
const resultNative = _.findIndex(floats, Number.isNaN); // Returns: 2In both cases, _.findIndex iterates through the float
array, invokes the predicate for each element, and immediately returns
the index of the first float that evaluates to true. If the
array contains only valid floating-point numbers and no NaN
values, it returns -1.
Alternative: Using _.indexOf for Direct Value Search
If the goal is to search for the literal value NaN
without writing a callback predicate, use _.indexOf instead
of _.findIndex:
const floats = [1.25, 4.5, NaN, 8.75];
const result = _.indexOf(floats, NaN); // Returns: 2Unlike native Array.prototype.indexOf, Lodash's
_.indexOf utilizes the SameValueZero equality algorithm,
allowing it to correctly identify NaN directly by
value.