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

Filter Unique Values

Kiểu đối tượng Set đã được giới thiệu trong ES6 và cùng với ..., ‘spread’ operator, chúng ta có thể sử dụng nó để tạo một mảng mới chỉ với các giá trị duy nhất.

Random String

Random String với độ dài tuỳ chọn

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

Spread Operator for Objects

Using the spread operator during an Object declaration will assign the properties of the referenced Object to the new Object.

Promise + gì

promise + gì