हमें एक 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