สมมติว่ามีอาร์เรย์ของสตริงสองอาร์เรย์ อาร์เรย์แรกมีสตริง 12 ตัว หนึ่งตัวสำหรับแต่ละเดือนของปี ดังนี้:
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
อาร์เรย์ที่สอง มีสตริงสองตัว แสดงช่วงของเดือน ดังนี้:
const monthsRange = ["aug", "oct"];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสองอาร์เรย์ดังกล่าว ฟังก์ชันควรเลือกเดือนทั้งหมดจากอาร์เรย์แรกที่อยู่ในช่วงที่ระบุโดยอาร์เรย์ช่วงที่สอง
เช่น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็น:
const output = ['aug', 'sep'];
สังเกตว่าเราไม่รวมเดือนปิดท้ายของช่วง ('oct') ในผลลัพธ์ เป็นส่วนหนึ่งของฟังก์ชันการทำงาน
ตัวอย่าง
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const range = ['aug', 'dec'];
const getMonthsInRange = (year, range) => {
const start = year.indexOf(range[0]);
const end = year.indexOf(range[1] || range[0]);
// ทำงานได้แม้ช่วงจะกลับด้าน
if (start <= end) {
return year.slice(start, end);
}
else {
return year.slice(start).concat(year.slice(0, end));
};
return false;
};
console.log(getMonthsInRange(year, range));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
[ 'aug', 'sep', 'oct', 'nov' ]