-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathflat.js
More file actions
28 lines (21 loc) · 735 Bytes
/
Copy pathflat.js
File metadata and controls
28 lines (21 loc) · 735 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// * 先不 TS 了,有点麻烦……
// * ================================================================================ original
{
const data = [1, [[2], [[3]]]];
console.log(data.flat());
console.log(data.flat(2));
console.log(data.flat(Infinity));
}
console.log('--------');
// * ================================================================================ our
{
const flat = (arr, depth = 1) => {
if (!Array.isArray(arr)) return arr;
if (depth <= 0) return [...arr];
return arr.reduce((a, e) => [...a, ...(Array.isArray(e) ? flat(e, depth - 1) : [e])], []);
};
const data = [1, [[2], [[3]]]];
console.log(flat(data));
console.log(flat(data, 2));
console.log(flat(data, Infinity));
}