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
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
Thethisvalue inside the function.
More examples
#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
-1before using the index.todos[-1]returnsundefined, and assigning to it creates a strange property instead. - For simple values,
indexOf()is enough.
Related entries
#- Array.prototype.find()Returns the first element that matches a condition, or undefined.
- Array.prototype.indexOf()Returns the index of the first occurrence of a value, or -1.
- Array.prototype.splice()Removes, replaces, or inserts elements in place, changing the array.
- Array.prototype.findLast()Returns the last element that matches a condition, searching the array from the end.
Spotted a mistake or missing an example? Write to us.