เราต้องเขียนฟังก์ชันที่รับอาร์เรย์และสตริงหลายตัวเป็นอาร์กิวเมนต์ หน้าที่คือตรวจสอบว่าสตริงเหล่านั้นมีอยู่ในอาร์เรย์หรือไม่ ถ้ามี เราต้องย้ายองค์ประกอบนั้นไปหน้าอาร์เรย์
ดังนั้น มาเขียนโค้ดสำหรับฟังก์ชันนี้
ตัวอย่าง
const arr = ['The', 'weather', 'today', 'is', 'a', 'bit', 'windy.']; const pushFront = (arr, ...strings) => { strings.forEach(el => { const index = arr.indexOf(el); if(index !== -1){ arr.unshift(arr.splice(index, 1)[0]); }; }); }; pushFront(arr, 'today', 'air', 'bit', 'windy.', 'rain'); console.log(arr);ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ 'windy.', 'bit', 'today', 'The', 'weather', 'is', 'a' ]