हमें एक JavaScript फ़ंक्शन लिखना है जो स्ट्रिंग्स की एक सरणी लेता है और उस स्ट्रिंग का इंडेक्स लौटाता है जो लंबाई में सबसे छोटी है।
हम केवल एक फॉर लूप का उपयोग करेंगे और उस स्ट्रिंग का इंडेक्स बनाए रखेंगे जो लंबाई में सबसे छोटी है।
आइए इस फ़ंक्शन के लिए कोड लिखते हैं:
उदाहरण
कोड निम्न होगा:
const arr = ['this', 'can', 'be', 'some', 'random', 'sentence']; const findSmallest = arr => { const creds = arr.reduce((acc, val, index) => { let { ind, len } = acc; if(val.length < len){ len = val.length; ind = index; }; return { ind, len }; }, { ind: -1, len: Infinity }); return arr[creds['ind']]; }; console.log(findSmallest(arr));आउटपुट
कंसोल में आउटपुट निम्न होगा:
be