เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์คำเป็นอาร์กิวเมนต์แรก อาร์กิวเมนต์ที่สองคือสตริงที่มีอักษรอังกฤษพิมพ์เล็ก 26 ตัว แต่เรียงในลำดับสุ่ม
ภารกิจคือตรวจสอบว่าคำในอาร์เรย์เรียงตามลำดับเล็กซิโครกราฟิกที่ถูกต้องตามลำดับที่อาร์กิวเมนต์ที่สองกำหนด ถ้าถูกต้องคืน true มิฉะนั้น false
ตัวอย่าง
ถ้าอาร์เรย์คำและลำดับคือ:
const arr = ['this', 'is', 'something', 'mad']; const order = 'hdetljnopqabcuvwxfgirsykmz';
ผลลัพธ์ควรเป็น:
const output = true;
เพราะ 't' อยู่ก่อน 'i' ซึ่งอยู่ก่อน 's' ซึ่งอยู่ก่อน 'm' ในสตริงลำดับ
ตัวอย่างโค้ด
const arr = ['this', 'is', 'something', 'mad'];
const order = 'hdetljnopqabcuvwxfgirsykmz';
const isPlacedCorrectly = (arr = [], order) => {
const { length } = arr;
for(let i = 0; i < length - 1; i++) {
for(let j = 0; j < arr[i].length; j++) {
if(order.indexOf(arr[i][j]) < order.indexOf(arr[i+1][j])) {
break;
} else if (order.indexOf(arr[i][j]) === order.indexOf(arr[i+1][j])) {
continue;
} else {
return false;
}
}
}
return true;
};
console.log(isPlacedCorrectly(arr, order));
ผลลัพธ์
true