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

การแบนอาร์เรย์巢狀 (Flatten) รวมค่า truthy/falsy - JavaScript

แบน (flatten) อาร์เรย์ nested หลายระดับ รวมค่า falsy (false, null) ไว้ด้วย โดยไม่ใช้ library functions

ตัวอย่าง

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

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

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];

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(arr.flatten());

วิธีทันสมัย (ES2019+)

const flatten = arr => arr.flat(Infinity);

ผลลัพธ์

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

ข้อควรระวัง: การเพิ่ม prototype method อาจ conflict กับ Array.prototype.flat() มาตรฐาน