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

แบนอาร์เรย์ซ้อน (Flatten Array) ด้วย Loop และ Recursion - JavaScript

ทำให้อาร์เรย์ซ้อน (Nested Array) กลายเป็นอาร์เรย์แบน (Flat Array) หนึ่งระดับ รวมค่า falsy (false, null) ด้วย

ตัวอย่าง

[[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]]
→ [1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6]

ตัวอย่างโค้ด (Prototype Extension)

const flatten = function() {
  let res = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      res.push(...this[i].flatten());
    } else {
      res.push(this[i]);
    }
  }
  return res;
};

Array.prototype.flatten = flatten;

console.log([[1,2,3], [4,5,[5,false,6,[5,8,null]]], [6]].flatten());

ผลลัพธ์

[1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6]

วิธีมาตรฐาน ES2019 (แนะนำ)

// ไม่ต้อง extend prototype
const arr = [[1,2,3], [4,5,[5,false,6,[5,8,null]]], [6]];
console.log(arr.flat(Infinity));

Array.prototype.flat(depth) เป็น Built-in ตั้งแต่ ES2019 ใช้ Infinity สำหรับแบนลึกไม่จำกัด