The JavaScript array.findIndex() method
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
<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
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()?
What is the difference between findIndex() and indexOf()?
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?
const i = arr.findIndex(o => o.id === id) — then assign or splice() at that index.