DEV Community

Keerthana M
Keerthana M

Posted on

Array search Methods.

Array Search Methods:

JavaScript Array indexOf()

  • The indexOf() method searches an array for an element value and returns its position.

Syntax:
Array.indexOf(item, start):
example:
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple");
console.log(position);
console.log(fruits);

output:
0
[ "Apple", "Orange", "Apple", "Mango" ]

example:
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple",3);
console.log(position);

output:
-1
(Array.indexOf() returns -1 if the item is not found.)

JavaScript Array lastIndexOf()

  • Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the last occurrence of the specified element.

syntax:
Array.lastIndexOf(item, start)
example:
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position1 = fruits.lastIndexOf("Apple",1);
console.log(position1);

output:
0

example:
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position1 = fruits.lastIndexOf("Apple");
console.log(position1);

output:
2

JavaScript Array includes():

  • This allows us to check if an element is present in an array (including NaN, unlike indexOf).

syntax:
Array.includes(search-item):
example:

const fruits1 = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits1.includes("Mango"));
console.log(fruits1.includes("kiwi"));

output:
true
false

JavaScript Array find():

  • The find() method returns the value of the first array element that passes a test function.

example:

const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
console.log(first);
console.log(numbers);

output:
25
[ 4, 9, 16, 25, 29 ]

JavaScript Array findIndex():

  • The findIndex() method returns the index of the first array element that passes a test function.

example:

const numbers1 = [4, 9, 16, 25, 29];
let first1 = numbers1.findIndex(myFunction1);
function myFunction1(value, index, array) {
return value > 18;
}
console.log(first1);
console.log(numbers1);

output:
3
[ 4, 9, 16, 25, 29 ]

JavaScript Array findLast() Method:

  • findLast() method that will start from the end of an array and return the value of the first element that satisfies a condition.

example:

const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x < 40);
console.log(high);
console.log(temp);

output:
30
[ 27, 28, 30, 40, 42, 35, 30 ]

JavaScript Array findLastIndex() Method:

  • The findLastIndex() method finds the index of the last element that satisfies a condition.

example:
const temp = [27, 28, 30, 40, 42, 35, 30];
let pos = temp.findLastIndex(x => x > 40);
console.log(pos);
console.log(temp);

output:
4
[ 27, 28, 30, 40, 42, 35, 30 ]

Top comments (0)