Skip to main content

findIndex() Method

The findIndex(callback) method is a modern replacement for the indexOf() method. It enables you to search with more complex conditions than just equality. It is used both for searching through an array of primitives and an array of objects.

array.findIndex((element, index, array) => {
// Callback body
});
  • Does not change the original array.
  • Iterates over the original array element by element.
  • Returns the index of the first element that satisfies a condition, that is, when the callback returns true.
  • If no element matches, that is, the callback returns false for all elements, the method returns -1.
const colorPickerOptions = [
{ label: "red", color: "#F44336" },
{ label: "green", color: "#4CAF50" },
{ label: "blue", color: "#2196F3" },
{ label: "pink", color: "#E91E63" },
{ label: "indigo", color: "#3F51B5" },
];

colorPickerOptions.findIndex(option => option.label === "blue"); // 2
colorPickerOptions.findIndex(option => option.label === "pink"); // 3
colorPickerOptions.findIndex(option => option.label === "white"); // -1