ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของตัวอักษรที่อาจมี 0 บางตัว ฟังก์ชันของเราควรปรับแต่งอาร์เรย์เพื่อให้ศูนย์ทั้งหมดถูกผลักไปที่จุดสิ้นสุด และองค์ประกอบที่ไม่ใช่ศูนย์ทั้งหมดจะคงตำแหน่งสัมพัทธ์ไว้
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [5, 0, 1, 0, -3, 0, 4, 6];
const moveAllZero = (arr = []) => {
const res = [];
let currIndex = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(el === 0){
res.push(0);
}else{
res.splice(currIndex, undefined, el);
currIndex++;
};
};
return res;
};
console.log(moveAllZero(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
[ 5, 1, -3, 4, 6, 0, 0, 0 ]