262

I am confused between the difference between the two function indexOf and find Index in an array.

The documentation says

findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise.

and

indexOf - Returns the index of the first occurrence of a value in an array.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • 16
    I think the difference is, one takes a function as an argument (enabling more sophisticated finds, like say you were looking for the first occurrence of a value with a specific substring instead of just the whole value), one just takes the value you're looking for. It's actually not a bad question. Downvotes without explanation should be down-votable. – Tim Consolazio Jan 03 '17 at 12:04
  • Sometimes it's best to start with the language specification (i.e. ECMA-262) and fill in the gaps with other material: [*Array.prototype.indexOf ( searchElement \[ , fromIndex \] )*](http://ecma-international.org/ecma-262/7.0/index.html#sec-array.prototype.indexof) vs [*Array.prototype.findIndex ( predicate \[ , thisArg \] )*](http://ecma-international.org/ecma-262/7.0/index.html#sec-array.prototype.findindex). – RobG Jan 03 '17 at 12:22
  • Thanks Tim and RobG – Rahul Singh Jan 03 '17 at 12:26

10 Answers10

379

The main difference are the parameters of these functions:

  • Array.prototype.indexOf() expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types (like string, number, or boolean).

  • Array.prototype.findIndex() expects a callback as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.

See the links for examples of both cases.

str
  • 42,689
  • 17
  • 109
  • 127
  • 11
    In case anyone is wondering what primitive types are js, they are things like string, number, boolean. – John Lee Oct 16 '18 at 20:47
  • 13
    Please note that `indexOf` will work to find objects. It is important to get the distinction that it accepts a single Object, not just a value, and compares by equality not value. Per Mozilla docs: ```indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).``` Please amend the `findIndex` explanation to only include the "or your find condition is more complex than just a single value or reference" limb to correct this as it led me astray originally. Thanks! – brokenalarms Dec 19 '18 at 20:06
  • 6
    @brokenalarms That is true, but only if you have a reference to an actual object in the array. For example, `[{a:1}].indexOf({a:1})` returns `-1` although the object seems to be the same (but it is not). Not sure whether this information is helpful in the answer as it might be confusing. If you need to know more about the exact language behaviour, you should read the specification. – str Dec 19 '18 at 20:47
  • Furthermore, indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator). – TheKingPinMirza Mar 10 '19 at 09:23
  • Worth noting however that `.indexOf(NaN)` will always return `-1` because `NaN==NaN` is always `false`. `NaN` *is* a primitive type because `typeof NaN` is `number` and so are `null` and `undefined`, so I would amend this to avoid saying `indexOf` works on primitive types – Matthew Jul 18 '19 at 18:41
  • @Matthew It does work on primitive types that are equal to themselves. – str Jul 18 '19 at 20:30
32

Simple - What kind of array structure are you using?

  • If array of objects, findIndex();
  • Else, indexOf().

"I want to find the index in an array of objects, with the key of "Orange".

let fruits = [
   { type: "Apple", quantity: 9 },
   { type: "Banana", quantity: 2},
   { type: "Orange", quantity: 8},
   { type: "Pear", quantity: 777}
];

let myIndex = fruits.findIndex(fruit => fruit.type === "Orange"); // Returns 2.

"I want to find the index in a simple array".

let fruits = [ "Apple", "Banana", "Pear", "Orange"];

let index = fruits.indexOf("Orange"); // Returns 3.
daCoda
  • 3,583
  • 5
  • 33
  • 38
21

FindIndex is useful if you want to find the first element that matches to your predicate: In W3C's example, there are numbers and matches if the customer's age above or equals to 18.

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

function checkAdult(age) {
    return age >= 18;
}

console.log(ages.findIndex(checkAdult));

console:

2

You can find an exact element index with the indexOf function of Array, but you can't pass a predicate. It is faster if you want to find a specific element:

var ages = [3, 10, 18, 20];
console.log(ages.indexOf(10));

returns:

1

Index counting starts at 0, so the first element index is 0.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Dániel Kis
  • 2,341
  • 5
  • 28
  • 51
19

The main difference between these is:

The findIndex() method gets a callback function like this:

var x = [1,2,3];
x.findIndex(x=> x==3); //returns 2

But the indexOf function gets just a value like this:

x.indexOf(3); // returns 2;

If you try to pass a callback into the indexOf it's return -1;

x.indexOf(x => x==3); //returns -1

And if try to pass value to findIndex it returns an error:

x.findIndex(3); //Uncaught TypeError: 3 is not a function at Array.findIndex (<anonymous>) at <anonymous>:1:3
6

Another difference is that with findIndex() the user can apply some function and find the element in the array which passes the test.

But the same is not true with indexOf() operator. A user can just check whether the particular element exists in the array or not.

Alok Ranjan
  • 967
  • 10
  • 10
5

You can also use includes:

[1, 2, 3].includes(2);      // true
[1, 2, 3].includes(4);      // false
[1, 2, 3].includes(3, 3);   // false

but I prefer the indexOf method:

var vals = [ "foo", "bar", 42, "baz" ];
if (~vals.indexOf( 42 )) {
  // found it!
}
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
zloctb
  • 10,592
  • 8
  • 70
  • 89
5

The main difference are the parameters of these functions:

-> Array.prototype.indexOf() :

   var fruits = ["Banana", "Orange", "Apple", "Mango"];
   var a = fruits.indexOf("Apple");
   The result of a will be: 2

->Array.prototype.findIndex() :

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

       function checkAdult(age) {
        return age >= 18;
       }

       function myFunction() {
         document.getElementById("demo").innerHTML = 
         ages.findIndex(checkAdult);
       }

       The result will be: 2
ashishdudhat
  • 180
  • 3
  • 9
3

You can try the codes below:-

let city = ['Delhi', 'mumbai']
const a = city.findIndex((item) => 
item.toLowerCase()==='delhi')
console.log(a) // returns 0

let c = city.indexOf('mumbai') // returns 1
console.log(c)
Gulsan Borbhuiya
  • 188
  • 2
  • 11
  • I don't think this code requires any explanation because this code looks very simple & easy to understand for a 'beginner' . Also, people who are beginners they face difficulty to understand complex code so I made it simple. So please don't say it low quality without understanding my intention. – Gulsan Borbhuiya Jul 15 '20 at 11:15
  • I didn't find anything low quality marked by system. – Gulsan Borbhuiya Jul 15 '20 at 13:47
1
  • findIndex accepts a callback as parameter and is best used with arrays of objects.
const employees = [
  { id: 1, name: "John", dob: 1999 },
  { id: 2, name: "Doe", dob: 2005 },
  { id: 3, name: "Marry", dob: 2001 },
  { id: 4, name: "Larry", dob: 1990 },
]

const output = employees.findIndex((elem) => elem.name === "Doe") // 1
  • indexOf accepts a value as a parameter.
let alphabets = ["a", "b", "c", "d", "e"]
alphabets.indexOf("c") // 2

Basir Payenda
  • 361
  • 3
  • 6
1

The difference is whether we can use conditions(boolean) to find an element's index.

.indexOf() can't have callback function as an argument(condition) to find an element's index.

.findIndex() can have callback function that returns boolean value (conditions) to find the first element's index that matches.

for example,

const names = ["John", "Princess", "Dominik", "Jay"];

// when we want to find an index of 'Jay'
const indexOfExample = names.indexOf("Jay");

// when we want to find an index of an element that has 4 or less characters
const findIndexExample = names.findIndex(function isShortName(name) {
    return name.length <= 4; 
})

// when we want to find an index of an element that has 7 or more characters
const findIndexExample2 = names.findIndex(name=>name.length>=7); 

console.log(indexOfExample) // 3
console.log(findIndexExample) // 0
console.log(findIndexExample2) // 1
kjs29
  • 21
  • 4