JavaScript ES6 – Array findIndex method

JavaScript findIndex() method is used to return index of first matching element from an array, will return -1 if no match was found.

Think of JavaScript array findIndex() method as: “I want to find the index number of an element within the object array.”

JavaScript findIndex() method is similar to indexOf() method but there is slightly usage difference between the 2 methods. You want to know the difference visit What are the difference between indexOf and findIndex method article.

array findIndex() parameters

JavaScript array findIndex() method consists of following parameters:

  • element – The current element being processed in the array
  • index – The index of the current element being processed in the array
  • array – The array findIndex() was called upon

Let’s see an example on how to use JavaScript array findIndex() method:

const products = [
  { type: "apple", quantity: 9 },
  { type: "banana", quantity: 2 },
  { type: "orange", quantity: 8 }

const appleIndex = products.findIndex((product) => product.type === 'banana');

// 1

In above example we are searching for index of apple in products object array, and 1 is returned as result which is expected.

This time we are passing second parameter indexFrom => 2, we want to start the search from array index 2 and skip array index 0 and 1, as result the output is 3.

array findIndex() usage and tips

  • Use findIndex() to find index of first matching element
  • If match found index is returned
  • No match found -1 is returned
%d bloggers like this: