Skip to content

Commit e7459fd

Browse files
committed
arrayIndex.js
1 parent baf5e4e commit e7459fd

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// 30. Find the Array Index with a Value
2+
3+
// Using indexOf() - Most Used
4+
5+
{
6+
const a = [10, 20, 30, 40, 50];
7+
8+
const index = a.indexOf(30);
9+
10+
console.log(index);
11+
12+
// Value not found
13+
const notFound = a.indexOf(60);
14+
console.log(notFound);
15+
}
16+
17+
// Using findIndex() for Complex Conditions
18+
19+
{
20+
const a = [10, 15, 20, 30, 40, 50];
21+
// find index of first value greater than 18
22+
23+
const index = a.findIndex((value) => value > 18);
24+
console.log(index);
25+
}
26+
27+
// Using for Loop for Custom Search
28+
29+
{
30+
const a = [5, 10, 15, 20, 25];
31+
let index = -1;
32+
// find index of value 20
33+
34+
for (let i = 0; i < a.length; i++) {
35+
if (a[i] === 25) {
36+
index = i;
37+
break;
38+
}
39+
}
40+
console.log(index);
41+
}
42+
43+
// Using lastIndexOf() for Reverse Search
44+
45+
{
46+
const a = [5, 10, 15, 1, 5];
47+
const index = a.lastIndexOf(10);
48+
console.log(index);
49+
}

0 commit comments

Comments
 (0)