Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Làm phẳng mảng lồng nhau (giữ giá trị falsy) - JavaScript

Viết hàm flatten() cho Array.prototype: làm phẳng mảng lồng nhau tùy ý, giữ lại giá trị falsy (false, null, 0, '').

Ví dụ

Đầu vào: [[1,2,3], [4,5,[5,false,6,[5,8,null]]], [6]]

Kết quả: [1,2,3,4,5,5,false,6,5,8,null,6]

Giải pháp

Mã triển khai đệ quy:

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());

Kết quả

Đầu ra trong console:

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

Hiện đại: Dùng arr.flat(Infinity) (ES2019).