Open In App

JavaScript TypedArray.prototype.findIndex() Method

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Method TypedArray.prototype.findIndex() of JavaScript returns the index of the first element in the typed array that fulfils the conditions specified by the testing function, if no elements satisfy it, -1 is returned, the findIndex() method takes a callback function as an argument and it returns an index if true and proceeds to next element if false, the original typed array does not get affected by findIndex().

Syntax

typedArray.findIndex(callbackFn, thisArg)

Parameters

  • callbackFn (Function): A Function that will run for every item in the array, it has three parameters:
    • element: (Number) Current element which is being processed in the typed array.
    • index: (Number, optional) The index of the current element being processed (optional).
    • typedArray: (TypedArray, optional) The typed array every() was called upon (optional).
  • thisArg: (Value, optional) A value to use as this when executing callbackFn (optional).

Return Value

It will return index of the first element that will satisfies the condition defined by callbackFn otherwise it will returns -1 if no element matches the condition.

Example 1: In the given below example we are finding index of first positive value using findIndex() method.

JavaScript
function findFirstPositiveIndex(typedArray) {
  return typedArray.findIndex(element => element > 0);
}

const float32Array = new Float32Array([-2.7, 0.5, 1.3, -0.8]);

const firstPositiveIndex = findFirstPositiveIndex(float32Array);

if (firstPositiveIndex !== -1) {
  console.log("Index of the first positive value:",
  firstPositiveIndex);
} else {
  console.log("No positive values found.");
}

Output
Index of the first positive value: 1

Example 2: In the below given example we are finding index of a specific value using findIndex() method.

JavaScript
function findValueIndex(typedArray, targetValue) {
  return typedArray.findIndex(element => element === targetValue);
}

const int8Array = new Int8Array([10, 20, 30, 40]);
const valueToFind = 20;

const targetIndex = findValueIndex(int8Array, valueToFind);

if (targetIndex !== -1) {
  console.log("Index of value", valueToFind, ":", targetIndex);
} else {
  console.log("Value", valueToFind,
  "not found in the array.");
}

Output
Index of value 20 : 1

Next Article

Similar Reads