typedArray.findIndex(callback) checks the elements from the first to the last and returns the index of the first one for which your callback returns a truthy value. If none passes, it returns -1. Use it when you need the position of an element, for example to overwrite it afterwards. It never changes the typed array by itself.
Remember
typedArray.findIndex((value, index, array) => test)
new Uint8Array([18, 22, 31]).findIndex(t => t > 20) โ 1
new Uint8Array([18, 22, 31]).findIndex(t => t > 99) โ -1
first match wins ยท returns the POSITION (or -1)
Syntax
findIndex() takes a callback and an optional thisArg. Call it on any typed array.
Get the position of the first element greater than 30.
ta.findIndex((v, i, arr) => ...)
The callback also gets the index and the typed array itself.
ta.findIndex((v) => v === 0)
Look for a value by equality. For plain values, indexOf() is shorter.
Built into JavaScript since ES2015 on all 11 typed array types. The index is always a plain number, even on BigInt typed arrays.
Library declarations
JavaScript
TypedArray.prototype.findIndex(callbackFn, thisArg)
// callbackFn(value, index, array) -> truthy: stop here
// returns the index of the first passing element, or -1
Parameters
Parameter
Description
callbackFn
A function called as (value, index, array). Return a truthy value for the element you want.
thisArg
Optional. The value used as this inside callbackFn (not for arrow functions).
Return Value
Return Value
Description
Number
The index of the first element that passed, or -1 if none did. It is the position-based twin of Array findIndex().
JavaScript Examples
Example 1 — Where Is the First Hot Reading?
Five temperatures sit in a Uint8Array. findIndex() reports where the first matching one lives.
JavaScript
const temps = new Uint8Array([18, 22, 31, 27, 35]);
console.log(temps.findIndex((t) => t > 30)); // 2
console.log(temps.findIndex((t, i, arr) => i > 0 && t < arr[i - 1])); // 3
console.log(temps.findIndex((t) => t === 18)); // 0