嵌套数组的合并,扁平化数组

嵌套数组的合并,扁平化数组

博客地址:https://ainyi.com/19

请写一个 flat 方法,实现扁平化嵌套数组
- 对于 [ [], [], [], ...] 数组里嵌套数组,有个需求:将里面的数组元素都放到外层数组,变成 [ , , , ...]
- 例如:let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
- 变成:arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];



- 倒是有几种方法:
 1 // 模拟:执行内含 10000 子数组 + 子数组有 13 个元素的数组
 2 let arr = [];
 3 
 4 for (let i = 0; i < 10000; i++) {
 5 arr.push([Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100]);
 6 }
 7 
 8 // 1. toString、split、map (支持多维数组~~~写法简便,速度又快)
 9 // 注意:数组元素非数字的时候需要改一下
10 // 用时:0.246s
11 let newArr = [];
12 let nowTime = new Date();
13 newArr = arr.toString().split(',').map(item => +item);
14 console.log(new Date() - nowTime, 'toString、split、map');
15 
16 
17 // 2. reduce + concat,(数组元素较短时推荐,写法简便)
18 // 用时:5.7s
19 newArr = [];
20 nowTime = new Date();
21 // 默认指定第一次的prev为[]
22 newArr = arr.reduce((arr, cur) => arr.concat(cur), []);
23 console.log(new Date() - nowTime, 'reduce');
24 
25 
26 // 3. 双重循环push,(数组元素较长时推荐,速度最快)
27 // 数组里面每个元素都必须是数组才行
28 // 诸如这样 [[],[],[],[]] 才行,如果这样 [1,[],2,[]] 不行,因为 for of 不能循环数字
29 // 用时:0.018 s
30 newArr = [];
31 nowTime = new Date();
32 for (let va of arr) {
33 for (let vq of va) {
34 newArr.push(vq);
35 }
36 }
37 console.log(new Date() - nowTime, 'for');
38 
39 
40 // 4. concat
41 // 用时:3.4 s
42 newArr = [];
43 nowTime = new Date();
44 for (let va of arr) {
45 newArr = newArr.concat(va);
46 }
47 console.log(new Date() - nowTime, 'concat');
48 
49 // 5. es6 的深拷贝数组 (速度最慢)
50 // 数组里面每个元素都必须是数组才行
51 // 诸如这样 [[],[],[],[]] 才行,如果这样 [1,[],2,[]] 不行,因为 ...后接不能是数字
52 // 用时:34 s
53 newArr = [];
54 nowTime = new Date();
55 for (let va of arr) {
56 newArr = [...newArr, ...va];
57 }
58 console.log(new Date() - nowTime, 'es6');

 

多维数组

 1 let arr = [1, [[2], [3, [4]], 5], [11, [21, [22, 22.1, 22.3], 31], 33, 40]];
 2 let newArr = [];
 3 
 4 // toString、split、map (写法简便)
 5 // 注意:数组元素非数字的时候需要改一下
 6 newArr = arr.toString().split(',').map(item => +item);
 7 console.log(newArr);
 8 
 9 // reduce 写法
10 let flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , []) : [arr];
11 newArr = flattenDeep(arr);
12 console.log(newArr);

数组的深拷贝

 1 // Array.from()
 2 var arr1 = [1,2,3];
 3 var arr2 = Array.from(arr1);
 4 // 数组尾部添加
 5 arr2.push(100);
 6 console.log(arr1,arr2); // [1, 2, 3] [1, 2, 3, 100]
 7 
 8 // [...arr] 使用这个也可以拼接数组,但是不推荐,效率太低
 9 var arr1 = [1,2,3];
10 // 超引用拷贝数组
11 var arr2 = [...arr1];
12 // 数组尾部添加
13 arr2.push(1000);
14 console.log(arr1,arr2); // [1, 2, 3] [1, 2, 3, 1000]
15 
16 function show(...args){
17 // 此时这个形式参数就是一个数组,我们可以直接push东西进来,如下
18 args.push(5);
19 console.log(args);
20 }
21 // 调用
22 show(1,2,3,4); // [1, 2, 3, 4, 5]

博客地址:https://ainyi.com/19

原文地址:https://www.cnblogs.com/ainyi/p/9329593.html