Skip to content

Commit b114c0e

Browse files
author
liguanliang
committed
array method flat flatMap pratice
1 parent 763737c commit b114c0e

File tree

3 files changed

+79
-4
lines changed

3 files changed

+79
-4
lines changed

Array/array_flat_flatMap.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* 递归造数据
3+
* @param {array} arr
4+
* @param {number} length
5+
* @param {number} deep
6+
*/
7+
function insertArray(arr, length, deep) {
8+
let len = length;
9+
if (!arr.length) {
10+
while (len--) {
11+
arr.push([])
12+
}
13+
if (!deep) {
14+
arr.forEach((item) => item[0] = Math.floor(Math.random() * 10))
15+
}
16+
} else {
17+
arr.forEach(element => {
18+
insertArray(element, len, deep)
19+
});
20+
}
21+
}
22+
/**
23+
* @param {number} deep=0
24+
* @param {number} length=0
25+
* @param {array} result=[]
26+
*/
27+
export function createNestedArray(deep = 0, length = 0, result = []) {
28+
29+
const resultArr = result || [];
30+
31+
while (deep--) {
32+
insertArray(resultArr, length, deep);
33+
}
34+
35+
return resultArr
36+
}
37+
38+
/**
39+
*
40+
* @param {} targetArr
41+
* @param {} deepth=0
42+
*/
43+
export function flat(targetArr, deepth = 0) {
44+
let flatArr = targetArr.flat(deepth);
45+
return flatArr;
46+
}
47+
48+
export function flatMap(flatMapArr, cb) {
49+
function _callback(currentValue, index, array, _this) {
50+
51+
return currentValue.join(',')
52+
}
53+
const callback = cb && typeof cb === "function" ? cb : _callback;
54+
let flatMapResult = flatMapArr.flatMap(callback);
55+
56+
return flatMapResult;
57+
}

Array/index.js

+20-2
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,23 @@ import {
22
lengthOperate,
33
funtionLoop
44
} from './lengthOperate.js';
5-
lengthOperate();
6-
funtionLoop();
5+
6+
import {
7+
flat,
8+
flatMap,
9+
createNestedArray
10+
} from "./array_flat_flatMap.js"
11+
12+
// lengthOperate();
13+
// funtionLoop();
14+
15+
const length = 3;
16+
const deep = 3;
17+
18+
const targetArr = createNestedArray(deep, length);
19+
20+
const flatResult = flat(targetArr, deep);
21+
console.log(flatResult, 'flatResult')
22+
23+
const flatMapResult = flatMap(targetArr);
24+
console.log(flatMapResult, 'flatMapResult')

index.html

+2-2
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373

7474
<!--<script src="js/timeCounter.js"></script>-->
7575

76-
<script src="js/index.js"></script>
76+
<!-- <script src="js/index.js"></script> -->
7777

7878
<!--<script src="js/30-seconds-of-code.js"></script>-->
7979

@@ -110,7 +110,7 @@
110110
<!-- <script src="./object/Object_defineproperty.js"></script>. -->
111111

112112
<!-- Array -->
113-
<!-- <script type="module" src="./Array/index.js"></script> -->
113+
<script type="module" src="./Array/index.js"></script>
114114

115115
<!-- RegExp -->
116116
<!-- <script type="module" src="./Reg/index.js"></script> -->

0 commit comments

Comments
 (0)