Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การย้ายศูนย์ทั้งหมดในอาร์เรย์ไปท้ายสุดใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าคงที่ (literals) ที่อาจมี 0 อยู่ ฟังก์ชันควรปรับอาร์เรย์ให้ 0 ทั้งหมดถูกย้ายไปท้ายสุด และสมาชิกที่ไม่ใช่ 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
]