References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.findIndex() method

Method JavaScript All modern browsers Updated
Quick answer

The findIndex() method returns the index of the first element that passes your test, or -1 if none do. users.findIndex(u => u.id === 42) gives the position of the matching user. It's the index-returning sibling of find(), and the condition-based version of indexOf().

Overview

findIndex() searches an array with a test function and returns the position of the first match. Where find() gives you the element itself, findIndex() gives you where it sits. If nothing matches, you get -1 — the same "not found" sentinel as indexOf().

The callback receives the usual element, index and array arguments and returns truthy for the element you want. You reach for the index (rather than the element) when you need to do something at that position — update an item in place, remove it with splice(), or insert next to it.

It's the condition-based counterpart to indexOf(): use indexOf() when you're looking for an exact value, and findIndex() when you need a test (which is what arrays of objects require). For searching from the end, there's findLastIndex().

Syntax

const i = array.findIndex(callbackFn)

array.findIndex((element, index, array) => {
  return /* true for the element you want */;
})

Parameters

The array.findIndex() method accepts the following parameters.

Parameter Description
callbackFn Test run for each element until one returns truthy. Receives (element, index, array).
thisArg Optional. A value to use as this inside the callback.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const tasks = [
    { id: 1, done: false },
    { id: 2, done: false },
    { id: 3, done: true }
  ];

  const i = tasks.findIndex(t => t.done);

  document.getElementById('out').textContent =
    'first done task is at index ' + i; // index 2
</script>

Best practices

  • Check the result against -1 for "not found".
  • Use findIndex() when you need the position; use find() for the element itself.
  • Pair it with splice() to update or remove the matched item.
  • For an exact-value search, indexOf() is simpler; use findIndex() when you need a condition.

Frequently asked questions

What does findIndex() return if nothing matches?
-1. Check the result before using it as an index.
What is the difference between find() and findIndex()?
find() returns the matching element; findIndex() returns its index (or -1).
What is the difference between findIndex() and indexOf()?
indexOf() matches an exact value; findIndex() runs a test function, which is what you need for arrays of objects.
How do I update an object in an array by id?
Find its index — const i = arr.findIndex(o => o.id === id) — then assign or splice() at that index.