เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของสตริงและส่งกลับดัชนีของสตริงที่มีความยาวสั้นที่สุด
เราจะใช้ for loop และรักษาดัชนีของสตริงที่มีความยาวสั้นที่สุด
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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