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

Async await in javascript

Async await in javascript

Converting Object to an Array

Converting Object to an Array

Random Number javascript

Random Number javascript

Rolling loading

Nguyên tắc là theo dõi các sự kiện cuộn trang và phân tích mối quan hệ thuộc tính giữa clientHeight , scrollTop và scrollHeight .

Spread Operator for Objects

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