เราต้องเขียนฟังก์ชันที่รับอาร์เรย์และย้ายศูนย์ทั้งหมดที่อยู่ในอาร์เรย์นั้นไปท้ายอาร์เรย์โดยไม่ใช้พื้นที่เพิ่มเติม เราจะใช้ Array.prototype.forEach() พร้อม Array.prototype.splice() และ Array.prototype.push()
โค้ดสำหรับฟังก์ชันจะเป็น
ตัวอย่าง
const arr = [34, 6, 76, 0, 0, 343, 90, 0, 32, 0, 34, 21, 54]; const moveZero = (arr) => { for(ind = 0; ind < arr.length; ind++){ const el = arr[ind]; if(el === 0){ arr.push(arr.splice(ind, 1)[0]); ind--; }; } }; moveZero(arr); console.log(arr);ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[34, 6, 76, 343, 90, 32, 34, 21, 54, 0, 0, 0, 0]