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

Merge Array

How to combine two sorted arrays into one? We can do this easily with the spread operator.

kiểm tra email trong javascript

kiểm tra email trong javascript

Await in a for loop

How to Await in a for loop

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

snowflake là gì

snowflake là gì? Năm 2010, Twitter có nguồn mở Snowflake, một thuật toán tạo ID duy nhất trên toàn cầu được sử dụng bởi nhóm nội bộ của nó, được dịch thành Snowflake.