Searching an element in Javascript Array

JavascriptWeb DevelopmentFront End Technology

Javascript provides a collection of functions that you can use to find elements in an array. Let's start with the most basic one. The indexOf function goes through the entire array and returns the index of the element you searched for, if it is found else it returns -1. For example,

Example

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

Output

This will give the output −

2
-1

There are other, more complex functions that you can use to make search more powerful. Let's look at find() method. The find() method returns the first object matching the condition you provide it as the callback() method. For example,

Example

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)

Output

This will give the output −

{ name: 'Richard', age: 21 }

But above result gives us an object. We can find the index of this object using the findIndex function. For example,

Example

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)

Output

This will give the output −

1

Note that the find() and findindex() functions take the callback as an argument and the callback takes arguments: element, index, array. These functions only give the first occurrence of the element. The indexOf function also takes another parameter, fromIndex, so that you can continue search from that point onwards. For example,

Example

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

Output

This will give the output −

1
4
raja
Published on 26-Jun-2018 17:55:27
Advertisements