जावास्क्रिप्ट का find() मेथड एरे में पहले एलिमेंट का मान लौटाने के लिए उपयोग किया जाता है, यदि कंडीशन पास होती है, अन्यथा रिटर्न वैल्यू undefined होती है।
सिंटैक्स इस प्रकार है:
array.find(function(value, index, arr), thisValue)
यहां, फंक्शन में value (वर्तमान एलिमेंट का मान), index (एरे इंडेक्स), और arr (एरे) होते हैं। thisValue पैरामीटर फंक्शन को पास किया जाने वाला मान है।
उदाहरण 1
<!DOCTYPE html>
<html>
<body>
<h2>रैंकिंग पॉइंट्स</h2>
<p>400 से ऊपर पहला पॉइंट प्राप्त करें...</p>
<button onclick="display()">परिणाम</button>
<p id="demo"></p>
<script>
var pointsArr = [50, 100, 200, 300, 400, 500, 600];
function pointsFunc(points) {
return points > 400;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
}
</script>
</body>
</html>
आउटपुट
500 (पहला एलिमेंट > 400)
उदाहरण 2 - Undefined केस
<!DOCTYPE html>
<html>
<body>
<h2>रैंकिंग पॉइंट्स</h2>
<p>400 से ऊपर पहला पॉइंट प्राप्त करें...</p>
<button onclick="display()">परिणाम</button>
<p id="demo"></p>
<script>
var pointsArr = [50, 100, 200, 300, 400];
function pointsFunc(points) {
return points > 400;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
}
</script>
</body>
</html>
आउटपुट
undefined (कोई एलिमेंट > 400 नहीं)
विस्तृत उपयोग
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true }
];
// पहला एक्टिव यूजर ढूंढें
const activeUser = users.find(user => user.active);
console.log(activeUser); // { id: 1, name: 'Alice', active: true }
// ऑब्जेक्ट में प्रॉपर्टी द्वारा
const user = users.find(({ id }) => id === 2);
console.log(user); // { id: 2, name: 'Bob', active: false }
// thisArg के साथ
const criteria = { minId: 2 };
const user2 = users.find(function(u) { return u.id >= this.minId; }, criteria);
console.log(user2); // { id: 2, name: 'Bob', active: false }
find vs filter vs findIndex
const arr = [1, 2, 3, 4, 5];
arr.find(x => x > 2); // 3 - पहला मैचिंग वैल्यू
arr.filter(x => x > 2); // [3, 4, 5] - सभी मैचिंग वैल्यूज
arr.findIndex(x => x > 2); // 2 - पहला मैचिंग इंडेक्स
नोट: find पहली मैच पर रुक जाता है (शॉर्ट-सर्किट), filter सभी एलिमेंट्स चेक करता है।