Javascript Array findIndex()

Introduction

The findIndex() method returns the element index by the provided testing function.

It returns -1, if no element passed the test.

arr.findIndex(callback( element[, index[, array]] )[, thisArg])
Parameter
Optional
Meaning
callback




Not




A function to execute on each value
It takes three arguments:
element - current element.
index - Optional, index of element.
array - Optional, array itself.
thisArg
Optional
Optional object to use as this when executing callback.

findIndex() will not process the elements appended to the array after the call.

Elements deleted are still visited.

Check get the index of the first element in the array that has a value of 18 or more.

var ages = [3, 10, 18, 20];

function checkAdult(age) {
  return age >= 18;
}
console.log(ages.findIndex(checkAdult));

The following example returns the index of the first prime number.

function isPrime(element) {
  let start = 2;/*  w  ww .j  av a2 s .c  o  m*/
  while (start <= Math.sqrt(element)) {
    if (element % start < 1) {
      return false;
    } else {
      start++;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 (array[2] is 7)

Find the index of a fruit using an arrow function:

const languages = ["HTML", "CSS", "Java", "C++", "Javascript"];

const index = languages.findIndex(lang => lang === "C++");

console.log(index); 
console.log(languages[index]);

More example

const people = [{/*from   w  ww  .j a va  2 s .  co  m*/
        name: "CSS",
        age: 27
    },
    {
        name: "HTML",
        age: 29
    }
];

console.log(people.find((element, index, array) => element.age < 28));
console.log(people.findIndex((element, index, array) => element.age < 28));

find() and findIndex() will continue searching once a match has been found.

const evens = [2, 4, 6];/*from  w w  w  . java 2 s  . com*/

// Last element of array will never be inspected after match is found 
evens.find((element, index, array) => {
    console.log(element);
    console.log(index);
    console.log(array);
    return element === 4;
});



PreviousNext

Related