JavaScriptArrays

Array.prototype.findIndex()

Returns the index of the first element that matches a condition, or -1.

Returns
The index of the first matching element, or -1.
Changes the original
No
On this page

Example

#
JavaScript
const lessons = ['Intro', 'Tags', 'Attributes', 'Forms']

console.log(lessons.findIndex((lesson) => lesson.startsWith('A')))
console.log(lessons.findIndex((lesson) => lesson === 'Tables'))
Console
2
-1

Definition and usage

#

The findIndex() method works like find(), but returns the index instead of the element. When nothing matches, the result is -1.

It comes in handy when you want to change or remove the found element in place, for example with splice(), or replace it with a new object.

Unlike indexOf(), it takes a function, so it can find objects by any field, not just values compared with ===.

Syntax

#
Syntax
array.findIndex(callbackFn)
array.findIndex(callbackFn, thisArg)

Parameters

#
  • callbackFn

    function (element, index, array)

    The testing function.
  • thisArg

    optional

    The this value inside the function.

More examples

#
Updating an element in an array
JavaScript
const todos = [
  { id: 1, done: false },
  { id: 2, done: false }
]

const index = todos.findIndex((todo) => todo.id === 2)
if (index !== -1) todos[index] = { ...todos[index], done: true }

console.log(todos)
Console
[{ id: 1, done: false }, { id: 2, done: true }]

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Always check for -1 before using the index. todos[-1] returns undefined, and assigning to it creates a strange property instead.
  • For simple values, indexOf() is enough.

Related entries

#

Spotted a mistake or missing an example? Write to us.