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

การหาความยาวคำที่สองสั้นที่สุดในประโยค - JavaScript

ฟังก์ชันนี้คืนความยาวของคำที่สองสั้นที่สุดในประโยค

ตัวอย่าง

// Input: 'This is a sample string'
// คำ: This(4), is(2), a(1), sample(6), string(6)
// เรียงความยาว: 1, 2, 4, 6, 6
// คำที่ 2 สั้นที่สุด: ความยาว 2

ตัวอย่างโค้ด

const str = 'This is a sample string';

const secondSmallest = str => {
  const strArr = str.split(' ');
  if (strArr.length < 2) return false;

  // แปลงเป็นอาร์เรย์ความยาว
  for (let i = 0; i < strArr.length; i++) {
    strArr[i] = strArr[i].length;
  }

  strArr.sort((a, b) => a - b);
  return strArr[1]; // index 1 = ตัวที่ 2
};

console.log(secondSmallest(str));

วิธีที่ทันสมัยกว่า

const secondSmallest = str => {
  const lengths = str.split(' ').map(w => w.length).sort((a, b) => a - b);
  return lengths.length >= 2 ? lengths[1] : false;
};

ผลลัพธ์

2