Make a summary every day, persistence is victory!

/** @date 2021-06-05 @description JavaScript array flattening */Copy the code

One (sequence)

In daily development, we often need to deal with the problem of array flattening. Now we have the flat method, and today we will implement it ourselves.

Ii (Implementation)

Using recursion, the handler is called again when an array is encountered:

const flat = (arr) => { const res = []; arr.forEach((item) => { if (Array.isArray(item)) { res.push(... flat(item)); } else { res.push(item); }}); return res; }; const arr = [1, [2, [3]], [4, 5, [6, 7, [8]]]]; console.log(flat(arr)); // [1, 2, 3, 4, 5, 6, 7, 8]Copy the code

Three (Extended)

A true flat function can pass a depth argument to indicate the recursive depth, which defaults to 1.

const arr = [1, [2, [3]], [4, 5, [6, 7, [8]]]]; console.log(arr.flat()); // [1, 2, [3], 4, 5, [6, 7, [8]]Copy the code

Implement depth to specify the depth of recursion:

const flat = (arr, depth = 1) => { if (depth === 0) { return arr; } const res = []; arr.forEach((item) => { if (Array.isArray(item)) { res.push(... flat(item, depth - 1)); } else { res.push(item); }}); return res; }; const arr = [1, [2, [3]], [4, 5, [6, 7, [8]]]]; console.log(flat(arr, 2)); // [ 1, 2, 3, 4, 5, 6, 7, [ 8 ] ] console.log(flat(arr, 3)); // [1, 2, 3, 4, 5, 6, 7, 8]Copy the code