जावास्क्रिप्ट का findIndex() मेथड एरे में पहले एलिमेंट का इंडेक्स लौटाने के लिए उपयोग किया जाता है, यदि कंडीशन पास होती है।
सिंटैक्स इस प्रकार है:
array.findIndex(function(currentValue, index, arr), thisValue)
उदाहरण 1
<!DOCTYPE html>
<html>
<body>
<h2>रैंक</h2>
<button onclick="display()">परिणाम</button>
<p id="demo"></p>
<p>उच्चतम रैंक वाले खिलाड़ी का इंडेक्स ढूंढ रहे हैं।</p>
<script>
var points = [100, 150, 200, 250, 300, 400];
function topRank(points) {
return points >= 400;
}
function display() {
document.getElementById("demo").innerHTML = "index = " + points.findIndex(topRank);
}
</script>
</body>
आउटपुट
इंडेक्स = 5 (400 इंडेक्स 5 पर है)
उदाहरण 2
<!DOCTYPE html>
<html>
<body>
<h2>रैंक</h2>
<button onclick="display()">परिणाम</button>
<p id="demo"></p>
<p>विशिष्ट रैंक पॉइंट्स वाले खिलाड़ी का इंडेक्स ढूंढ रहे हैं।</p>
<script>
var points = [100, 150, 200, 250, 300, 400];
function topRank(points) {
return points == 200;
}
function display() {
document.getElementById("demo").innerHTML = "index = " + points.findIndex(topRank);
}
</script>
</body>
आउटपुट
इंडेक्स = 2 (200 इंडेक्स 2 पर है)
विस्तृत उपयोग
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
// ऑब्जेक्ट प्रॉपर्टी द्वारा खोजें
const index = users.findIndex(user => user.age > 28);
console.log(index); // 1 (Bob)
// thisArg के साथ
const threshold = { minAge: 30 };
const index2 = users.findIndex(function(user) {
return user.age >= this.minAge;
}, threshold);
console.log(index2); // 2 (Charlie)
// न मिलने पर -1 लौटाता है
users.findIndex(user => user.age > 100); // -1
findIndex vs indexOf
const arr = [1, 2, 3, 2, 1];
arr.indexOf(2); // 1 - पहला 2 (सटीक मैच)
arr.findIndex(x => x === 2); // 1 - समान
// लेकिन findIndex अधिक शक्तिशाली है:
arr.findIndex(x => x > 2); // 2 - पहला 3
arr.findIndex(x => x % 2 === 0); // 1 - पहला इवन नंबर