Skip to content

Commit 3b5be09

Browse files
committed
feat: add flat function
1 parent 6bdf0df commit 3b5be09

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

js/flat.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
*
3+
* @param {*} array 深层嵌套的数据
4+
* @returns array 新数组
5+
*/
6+
const flat1 = (array) => {
7+
return array.reduce((result, it) => {
8+
return result.concat(Array.isArray(it) ? flat1(it) : it);
9+
}, []);
10+
};
11+
12+
let arr1 = [1, [2, 3, 4], [5, [6, [7, [8]]]]];
13+
console.log(flat1(arr1));
14+
15+
// js原生的flat方法
16+
/**
17+
*
18+
* @param {*} array 深层嵌套的数据
19+
* @returns 新数组
20+
*/
21+
const flat2 = (array) => {
22+
return array.flat(Infinity);
23+
};
24+
25+
let arr2 = [1, [2, 3, 4], [5, [6, [7, [8]]]]];
26+
27+
console.log(flat2(arr2));
28+
29+
const flat3 = (array) => {
30+
const result = [];
31+
const stack = [...array];
32+
33+
while (stack.length !== 0) {
34+
const val = stack.pop();
35+
if (Array.isArray(val)) {
36+
stack.push(...val);
37+
} else {
38+
result.unshift(val);
39+
}
40+
}
41+
return result;
42+
};
43+
44+
let arr3 = [1, [2, 3, 4], [5, [6, [7, [8]]]]];
45+
46+
console.log(flat3(arr3));

leetcode/greedy_algorithm/jump_game

61.6 KB
Binary file not shown.

0 commit comments

Comments
 (0)