findIndex()

Introduction

The findIndex() method is a useful JavaScript array method that searches an array and returns the index of the first element that satisfies a specified condition.

Unlike find(), which returns the element itself, findIndex() returns the position (index) of the matching element.

If no element satisfies the condition, findIndex() returns -1.

For automation engineers, findIndex() is commonly used to locate the position of objects in API responses, identify test data records, search JSON arrays, update array elements, and process data-driven test cases.


What is findIndex()?

The findIndex() method executes a callback function once for each array element.

It returns the index of the first element for which the callback returns true.

If no element matches, it returns -1.


Syntax

array.findIndex(function(currentValue, index, array) {

    // Return true or false

});

Or using an arrow function:

array.findIndex((currentValue, index, array) => {

    // Return true or false

});

Parameters

ParameterDescription
currentValueThe current element being processed.
index (optional)The index of the current element.
array (optional)The array on which findIndex() was called.

Return Value

The findIndex() method returns:

  • The index of the first matching element, or

  • -1 if no matching element is found.


Example 1: Find the Index of a Number

const numbers = [5, 10, 15, 20];

const index = numbers.findIndex(number => number > 10);

console.log(index);

Output

2

The value 15 is the first number greater than 10, and its index is 2.


Example 2: Find the Index of an Even Number

const numbers = [3, 7, 8, 10];

const index = numbers.findIndex(number => number % 2 === 0);

console.log(index);

Output

2

Example 3: Find the Index of a String

const fruits = [

    "Apple",

    "Mango",

    "Orange"

];

const index = fruits.findIndex(item => item === "Mango");

console.log(index);

Output

1

Example 4: Using the Index Parameter

const values = [10, 20, 30, 40];

const result = values.findIndex((value, index) => index === 3);

console.log(result);

Output

3

Example 5: Find the Index of an Object

const employees = [

    { id: 1, name: "John" },

    { id: 2, name: "Alice" },

    { id: 3, name: "David" }

];

const employeeIndex = employees.findIndex(emp => emp.id === 2);

console.log(employeeIndex);

Output

1

Example 6: No Matching Element

const numbers = [10, 20, 30];

const index = numbers.findIndex(number => number > 100);

console.log(index);

Output

-1

Real-World Example

Find the index of an available product.

const products = [

    { name: "Laptop", available: false },

    { name: "Mouse", available: true },

    { name: "Keyboard", available: true }

];

const productIndex = products.findIndex(product => product.available);

console.log(productIndex);

Output

1

Another example:

Find the first high-value order.

const orders = [250, 800, 1500, 2000];

const orderIndex = orders.findIndex(amount => amount >= 1000);

console.log(orderIndex);

Output

2

Automation Testing Example

The findIndex() method is widely used in automation testing to locate the position of specific records and update or validate them.

Playwright Example

Find the index of the active page.

const pages = [

    { title: "Home", active: false },

    { title: "Products", active: true },

    { title: "Contact", active: true }

];

const activePageIndex = pages.findIndex(page => page.active);

console.log(activePageIndex);

Output

1

Selenium Example

Find the index of a URL.

const urls = [

    "https://example.com",

    "https://google.com",

    "https://github.com"

];

const index = urls.findIndex(url => url.includes("google"));

console.log(index);

Output

1

Cypress Example

Find the index of a failed test.

const tests = [

    { name: "Login", passed: true },

    { name: "Checkout", passed: false },

    { name: "Logout", passed: true }

];

const failedTestIndex = tests.findIndex(test => !test.passed);

console.log(failedTestIndex);

Output

1

API Testing Example

Find the index of a user.

const users = [

    { id: 101, name: "John" },

    { id: 102, name: "Alice" },

    { id: 103, name: "David" }

];

const userIndex = users.findIndex(user => user.id === 102);

console.log(userIndex);

Output

1

Data-Driven Testing Example

Find the index of an active user.

const users = [

    { username: "admin", active: false },

    { username: "manager", active: true },

    { username: "guest", active: true }

];

const activeUserIndex = users.findIndex(user => user.active);

console.log(activeUserIndex);

Output

1

findIndex() vs find()

FeaturefindIndex()find()
ReturnsIndex of the first matching elementFirst matching element
No match found-1undefined
Stops after first matchYesYes
Original arrayUnchangedUnchanged

Common Mistakes

Expecting the Element Instead of the Index

Incorrect:

const result = numbers.findIndex(number => number > 10);

console.log(result * 2);

Remember that findIndex() returns the position, not the value.


Forgetting to Return a Condition

Incorrect:

const index = numbers.findIndex(number => {

    number > 10;

});

Output

-1

Correct:

const index = numbers.findIndex(number => number > 10);

Ignoring -1

Always check whether the returned value is -1 before using it.

if (index !== -1) {

    console.log("Element found");

}

Best Practices

Use findIndex() When You Need the Position

If you need the actual element, use find() instead.


Check for -1

Always verify that a matching element was found before accessing the array using the returned index.


Prefer Arrow Functions

Arrow functions make callback code concise and readable.


Use Clear Conditions

Write meaningful comparison expressions for better readability.


Conclusion

The findIndex() method is an essential JavaScript array method for locating the position of the first element that matches a specified condition. It provides an efficient way to search arrays when the index is required instead of the element itself.

For automation engineers, findIndex() is especially useful for locating records in API responses, updating JSON objects, validating test data, and processing arrays in data-driven automation.

Mastering findIndex() helps you write cleaner, more efficient, and maintainable JavaScript code.


Frequently Asked Questions (FAQs)

What is the findIndex() method?

findIndex() searches an array and returns the index of the first element that satisfies a specified condition.


What happens if no element matches?

It returns -1.


Does findIndex() modify the original array?

No. The original array remains unchanged.


What is the difference between find() and findIndex()?

find() returns the matching element, while findIndex() returns the index of the matching element.


Can findIndex() be used with arrays of objects?

Yes. It is commonly used to locate the position of objects based on their properties.


Why is findIndex() useful in automation testing?

Automation engineers use findIndex() to locate records in API responses, update test data, validate JSON objects, identify failed test cases, and process collections efficiently.


Key Takeaways

  • findIndex() returns the index of the first matching element.

  • If no element matches, it returns -1.

  • The original array remains unchanged.

  • It stops searching after finding the first match.

  • It works with primitive values and objects.

  • Use find() when you need the element itself.

  • Always check for -1 before using the returned index.

  • Arrow functions are commonly used with findIndex().

  • findIndex() is widely used in Playwright, Selenium, Cypress, API testing, and data-driven automation.

  • Mastering findIndex() is essential for efficient array searching in JavaScript.