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

ลบค่า Undefined/Empty ออกจากอาร์เรย์ In-place - JavaScript

ลบช่องว่าง (Empty Slots / Undefined) ออกจากอาร์เรย์ แบบ In-place (แก้ไขอาร์เรย์เดิม)

ตัวอย่าง

[4, 6, , 45, 3, 345, , 56, 6] → [4, 6, 45, 3, 345, 56, 6]

ตัวอย่างโค้ด

const eliminateUndefined = arr => {
  for (let i = 0; i < arr.length; ) {
    if (typeof arr[i] !== 'undefined') {
      i++;
      continue;
    }
    arr.splice(i, 1);
  }
};

const arr = [4, 6, , 45, 3, 345, , 56, 6];
eliminateUndefined(arr);
console.log(arr);

ผลลัพธ์

[ 4, 6, 45, 3, 345, 56, 6 ]

วิธีแบบ Built-in (สร้างอาร์เรย์ใหม่)

// ลบ empty slots และ undefined
const clean = arr => arr.filter(x => typeof x !== 'undefined');

// หรือใช้ flat() (ลบ empty slots ทุกระดับ)
const clean = arr => arr.flat();

flat() โดยไม่ระบุ depth จะลบ Empty Slots ออกได้ (แต่จะแบนอาร์เรย์ซ้อนด้วย)