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

Sự khác biệt giữa substr và substring

Sự khác biệt giữa substr() và substring() chức năng trong JS là gì?

How to reverse an Array?

Reversing an array in JS is really simple with the standard array method. Like below

Đếm có bao nhiêu items giống nhau trong một array

reduce javascript. Đếm có bao nhiêu items giống nhau trong một array

10 mẹo sử dụng array và object trong javascript

10 mẹo sử dụng array và object trong javascript

Spread Operator for Objects

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