Sử dụng reduce và concat làm phẳng một array

array,tipjs

Array.reduce()Array.concat() có thể giúp chúng ta làm phẳng một Array. depth là số lần đệ quy.

const flatten = (arr, depth = 1) =>
  depth != 1
    ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
    : arr.reduce((a, v) => a.concat(v), []);

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

Có thể bạn đã miss một số snippets code

Promise + gì

promise + gì

Async await in javascript

Async await in javascript

lỗi access-control-allow-origin và cách khắc phục

lỗi access-control-allow-origin và cách khắc phục trong express, nodejs

encode/decode base64 with JS

Encoding to base64 is done with the btoa command

try/catch es10

An update for developer convience allows the use of try/catch without an explicit e Error reference in the catch call.