Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาสตริงที่สั้นที่สุดในอาร์เรย์ - JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของสตริงและคืนค่าดัชนีของสตริงที่สั้นที่สุด

เราจะใช้ลูป for และเก็บดัชนีของสตริงที่สั้นที่สุด

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

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