When should I use .findIndex() vs .indexOf()?

Question

When should I use .findIndex() vs .indexOf()?

Answer

We should use .indexOf() when we want to find the index of the first occurrence of a specific value in an array.
For example:

var myArrayOfStrings = ['this', 'is', 'my', 'array', 'of', 'strings'];

console.log(myArrayOfStrings.indexOf('my')); //logs `2` to the console because the string value `'my'` is at the 2nd index (arrays in JS start at 0)

We should use .findIndex() when we want to check a condition for each element of an array, until the condition is met, and get the index of the first array element that passes said condition.
For example:

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

function isGreaterThanNine (num) {
  return num > 9; //returns a boolean value, true if num is greater than 9, false if num is less than or equal to 9
}

console.log(myArray.findIndex(isGreaterThanNine)); //9 is logged to the console as the value at the 9th index is the first value that passes the condition provided by the isGreaterThanNine function

That would be the first occurrence of the value in the array. If there are multi instances of that value, they will never be found. findIndex() does nothing to solve this dilemma. Obviously it represents another problem to solve.

4 Likes

In other words, findIndex() can do the same and a bit more?

findIndex() is a conditional iterator. Where we can give indexOf() a static value and have it search for it, we give findIndex() a function that will test values and return the index of the first value that meets the given condition.

11 Likes

@mtf
While the methods indexOf() and findIndex() may not return all the indices of a key we which to find, we can still play around with them a bit to write functions which may run faster than just straight up using a for loop. check this out:

function ruronite(arr,keyToFind){
let indices = ;
let index = arr.indexOf(keyToFind);
indices.push(index)
while (index > -1){
index = arr.indexOf(keyToFind,index + 1);
if (index > -1){
indices.push(index)
}
}
return indices
}
const beasts = [‘ant’, ‘bison’, ‘camel’, ‘duck’, ‘bison’];

console.log(ruronite(beasts,“bison”))
// log [1,4]

1 Like

Not sure we should push anything to the array before the loop. Consider the following,

function getIndices(arr, item){
  const indices = [];
  let index = -1;
  while (true){
    index = arr.indexOf(item, ++index);
    if (index < 0) break;
    indices.push(index)
  }
  return indices
}
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(getIndices(beasts, 'bison'))    //  [ 1, 4 ]

Note

++index

The increment operator is prefixed so the operation takes place before indexOf()

1 Like

yea that’s true . I think I did that so we don’t even have to enter the while loop if the element doesn’t exist in the array. Both ways work though. :slightly_smiling_face:

1 Like

In the first example, if I put in a condition which places an element of an array equal to “my” so the result would be:

console.log(myArrayOfStrings.findIndex(element => element === ‘my’)); //-> 2

IMO, with their limitation (of finding the first occurrence), the choice of using findIndex() or indexOf is up to the user, whichever one is comfortable with, as long as the code is clear and easier to understand to the readers within the context of the program. I second aubsrey on finding its value without taxing our codes unnecessarily, use indexOf(‘my’).

Hello everyone… I know this is an old post, I am posting my code for critique: (It was approved instantly and I would like your feedback to know how I could maybe have done this another way with the same positive results)…Thanks to all in advance :blush:

const findMyKeys = arr => {

let word = ‘keys’;

if (arr.includes(word)) {

 return arr.indexOf(word);

} else {

 return -1;

}

};

1 Like

Hello! You can make it shorter:

const findMyKeys = arr => arr.indexOf('keys');

Thanks for your example …Helped a lot!

Or, make use this way

const findMyKeys = (arr) => {
let chkKey = arr.findIndex(isKey => isKey === “keys”)
return chkKey
}