This page looks best with JavaScript enabled

indexOf vs. find for Arrays

 ·   ·  ☕ 1 min read

Both indexOf() and find() are used for finding a pattern within an array. How are they different?

indexOf requires the exact string to search within array.

1
2
3
4
const nums = [1, 3, 5, 7, 9];

console.log(nums.indexOf(3));
// 1

indexOf behaves very much like its string counterpart which helps to search a substring within a string. You cannot do anything more complicated than that.

You can provide super powers to your ‘locating an element’ quest using find and findIndex.

1
2
3
4
5
6
7
const nums = [1, 3, 5, 7, 9];

console.log(nums.find(val => val % 3 == 0));
// 3 (value of first number divisible by 3)

console.log(nums.findIndex(val => val % 3 == 0));
// 1 (position)
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things