278

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.

2
  • 19
    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. Commented Jan 3, 2017 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 ] ) vs Array.prototype.findIndex ( predicate [ , thisArg ] ). Commented Jan 3, 2017 at 12:22

10 Answers 10

402

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.

Sign up to request clarification or add additional context in comments.

6 Comments

In case anyone is wondering what primitive types are js, they are things like string, number, boolean.
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 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.
Furthermore, indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).
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
|
37

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.

Comments

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.

Comments

21

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

Comments

7

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.

Comments

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

Comments

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!
}

2 Comments

also includes requires a polyfill for IE
indexOf is much faster as well.
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)

2 Comments

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.
I didn't find anything low quality marked by system.
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.