Searching an element in Javascript Array

JavaScript provides several methods to search for elements in arrays. Each method has its own use case depending on whether you're searching for primitive values or complex objects.

Using indexOf() for Primitive Values

The indexOf() method searches through the array and returns the index of the first matching element, or -1 if not found.

let people = ["Harry", "Martha", "John", "Sam"];
console.log(people.indexOf("John"));
console.log(people.indexOf("Jim"));
2
-1

Using find() for Complex Objects

The find() method returns the first element that matches the condition provided in the callback function.

let people = [{
    name: 'Agnes',
    age: 25
}, {
    name: 'Richard',
    age: 21
}, {
    name: 'Zoe',
    age: 35
}];
let personNameStartsWithR = people.find(person => person.name[0] === 'R');
console.log(personNameStartsWithR);
{ name: 'Richard', age: 21 }

Using findIndex() to Get the Position

The findIndex() method returns the index of the first element that matches the condition, rather than the element itself.

let people = [{
    name: 'Agnes',
    age: 25
}, {
    name: 'Richard',
    age: 21
}, {
    name: 'Zoe',
    age: 35
}];
let personNameStartsWithR = people.findIndex(person => person.name[0] === 'R');
console.log(personNameStartsWithR);
1

Using fromIndex Parameter

The indexOf() method accepts a second parameter fromIndex to start searching from a specific position.

let people = ["Harry", "Martha", "John", "Sam", "Martha"];
console.log(people.indexOf("Martha"));
console.log(people.indexOf("Martha", 3));
1
4

Comparison of Search Methods

Method Return Value Use Case
indexOf() Index or -1 Primitive values
find() Element or undefined Complex objects
findIndex() Index or -1 Index of complex objects

Key Points

  • All these methods return only the first occurrence of the matching element
  • The find() and findIndex() methods accept callback functions with parameters: element, index, array
  • Use indexOf() for simple value searches and find()/findIndex() for condition-based searches

Conclusion

Choose indexOf() for searching primitive values, and find() or findIndex() when you need to search objects with specific conditions. All methods return the first match found in the array.

Updated on: 2026-03-15T23:18:59+05:30

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements