Array.find() मेथड
find() ऐरे में पहले एलिमेंट का मान लौटाता है जो टेस्ट फंक्शन को पास करता है। कोई पास न करे तो undefined लौटाता है।
सिंटैक्स
array.find(callback(element, index, array), thisArg)
उदाहरण
<html> <body> <p id="demo"></p> <script>
var prices = [3000, 21000, 28000, 20000, 15500];
function checkCost(cost) {
return cost >= 12000;
}
var found = prices.find(checkCost);
document.getElementById("demo").innerHTML = found;
</script> </body> </html>
आउटपुट
21000
व्याख्या
- 3000 < 12000 ❌
- 21000 ≥ 12000 ✅ → पहला मैच, 21000 लौटाएं
- बाकी चेक नहीं (शॉर्ट-सर्किट)
आधुनिक सिंटैक्स
<script>
var prices = [3000, 21000, 28000, 20000, 15500];
// एरो फंक्शन
var found = prices.find(p => p >= 12000); // 21000
// ऑब्जेक्ट्स में खोज
var products = [
{id: 1, name: "लैपटॉप", price: 50000},
{id: 2, name: "माउस", price: 500},
{id: 3, name: "कीबोर्ड", price: 2000}
];
var expensive = products.find(p => p.price > 10000);
// {id: 1, name: "लैपटॉप", price: 50000}
var cheap = products.find(p => p.price < 1000);
// {id: 2, name: "माउस", price: 500}
</script>
find() vs filter() vs findIndex()
| मेथड | रिटर्न्स | कितने एलिमेंट्स | उपयोग |
|---|---|---|---|
find() | पहला मिलान (वैल्यू) | 1 | सिंगल आइटम खोज |
filter() | सभी मिलान (ऐरे) | 0+ | सभी मिलान चाहिए |
findIndex() | पहला मिलान (इंडेक्स) | 1 | पोजीशन चाहिए |
indexOf() | इंडेक्स | 1 | सटीक मान खोज |
सामान्य गलतियाँ
<script>
// ❌ गलत: find बूलियन नहीं लौटाता
if (arr.find(x => x > 5)) { ... } // काम करता है लेकिन भ्रामक
// ✅ सही: some() बूलियन के लिए
if (arr.some(x => x > 5)) { ... }
// ❌ गलत: undefined चेक भूलना
var item = arr.find(x => x.id === 999);
console.log(item.name); // TypeError यदि नहीं मिला!
// ✅ सही: ऑप्शनल चेनिंग या चेक
console.log(item?.name); // undefined (सेफ)
</script>