close

DEV Community

SIYAMALA G
SIYAMALA G

Posted on

Array Search

Array Search means finding a value inside an array.

1. includes()

=>checks if value exists

const a=[2,99,45,76,54];

console.log(a.includes(45));
console.log(a.includes(12));
Enter fullscreen mode Exit fullscreen mode
//true
//false
Enter fullscreen mode Exit fullscreen mode

2. indexOf()

=>finds indexvalue and it print first occurrence

const a=[2,99,45,76,45,54];

console.log(a.indexOf(45));
Enter fullscreen mode Exit fullscreen mode
2  //first occurance
Enter fullscreen mode Exit fullscreen mode

3.lastIndexOf()

=>same as indexOf but it print last occurance

const a=[2,99,45,76,45,54];

console.log(a.lastIndexOf(45));
Enter fullscreen mode Exit fullscreen mode
4 //last occurance
Enter fullscreen mode Exit fullscreen mode

4.find()

=>finds value with condition and return first matching value.
=>check from frist(start->end).

const a=[2,99,45,76,54];
const b=a.find(n=>n>40);
console.log(b);
Enter fullscreen mode Exit fullscreen mode
99
Enter fullscreen mode Exit fullscreen mode

5.findLast()

=>same as find but it check from last (end->start)

const a=[2,99,45,76,54];
const b=a.find(n=>n>40);
console.log(b);
Enter fullscreen mode Exit fullscreen mode
54
Enter fullscreen mode Exit fullscreen mode

6.findIndex()

=>find indexvalue with condition.
=>return first matching indexvalue.

const a=[2,9,4,7,14];
const b=a.findIndex(n=>n>40);
console.log(b);

const a=[2,8,4,77,14];
const b=a.findIndex(n=>n>40);
console.log(b);
Enter fullscreen mode Exit fullscreen mode
-1  //no match

3 
Enter fullscreen mode Exit fullscreen mode

7.findLastIndex()

=>same as findIndex but it return last matching indexvalue.

const a=[2,9,4,6,8];
const b=a.findLastIndex(n=>n>5);
console.log(b);
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)