สมมติว่าเรามีอาร์เรย์ที่มีชื่อของบางคนดังนี้:
const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเช่นอาร์กิวเมนต์แรกและอักขระตัวพิมพ์เล็กสองตัวเป็นอาร์กิวเมนต์ที่สองและสาม จากนั้น ฟังก์ชันของเราควรกรองอาร์เรย์ให้มีเฉพาะองค์ประกอบที่ขึ้นต้นด้วยตัวอักษรที่อยู่ในช่วงที่ระบุโดยอาร์กิวเมนต์ที่สองและสาม
ดังนั้น หากอาร์กิวเมนต์ที่สองและสามคือ 'a' และ 'j' ตามลำดับ ผลลัพธ์ควรเป็น -
const output = ['Amy','Dolly','Jason'];
ตัวอย่าง
ให้เราเขียนโค้ด -
const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
const filterByAlphaRange = (arr = [], start = 'a', end = 'z') => {
const isGreater = (c1, c2) => c1 >= c2;
const isSmaller = (c1, c2) => c1 <= c2;
const filtered = arr.filter(el => {
const [firstChar] = el.toLowerCase();
return isGreater(firstChar, start) && isSmaller(firstChar, end);
});
return filtered;
};
console.log(filterByAlphaRange(arr, 'a', 'j')); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ 'Amy', 'Dolly', 'Jason' ]