天天看點

嵌套數組的合并,扁平化數組

部落格位址: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;

倒是有幾種方法:

// 模拟:執行内含 10000 子數組 + 子數組有 13 個元素的數組
let arr = [];

for (let i = 0; i < 10000; i++) {
  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]);
}

// 1. toString、split、map (支援多元數組~~~寫法簡便,速度又快)
// 全部是數字類型,重新映射 map,不是字元串類型就不用 map
// 用時:0.246s
let newArr = [];
let nowTime = new Date();
newArr = arr.toString().split(',').map(item => +item);
console.log(new Date() - nowTime, 'toString、split、map');

// 全部數字類型的:arr.toString().split(',').map(Number); 
// 全部字元串類型的:arr.toString().split(','); 



// 2. reduce + concat,(數組元素較短時推薦,寫法簡便)
// 用時:5.7s
newArr = [];
nowTime = new Date();
// 預設指定第一次的prev為[]
newArr = arr.reduce((arr, cur) => arr.concat(cur), []);
console.log(new Date() - nowTime, 'reduce');


// 3. 雙重循環push,(數組元素較長時推薦,速度最快)
// 數組裡面每個元素都必須是數組才行
// 諸如這樣 [[],[],[],[]] 才行,如果這樣 [1,[],2,[]] 不行,因為 for of 不能循環數字
// 用時:0.018 s
newArr = [];
nowTime = new Date();
for (let va of arr) {
  for (let vq of va) {
    newArr.push(vq);
  }
}
console.log(new Date() - nowTime, 'for');


// 4. concat
// 用時:3.4 s
newArr = [];
nowTime = new Date();
for (let va of arr) {
  newArr = newArr.concat(va);
}
console.log(new Date() - nowTime, 'concat');

// 5. es6 的深拷貝數組 (速度最慢)
// 數組裡面每個元素都必須是數組才行
// 諸如這樣 [[],[],[],[]] 才行,如果這樣 [1,[],2,[]] 不行,因為 ...後接不能是數字
// 用時:34 s
newArr = [];
nowTime = new Date();
for (let va of arr) {
  newArr = [...newArr, ...va];
}
console.log(new Date() - nowTime, 'es6');           

複制

多元數組

let arr = [1, [[2], [3, [4]], 5], [11, [21, [22, 22.1, 22.3], 31], 33, 40]];
let newArr = [];

// toString、split、map (寫法簡便)
// 注意:數組元素非數字的時候不需要 map
newArr = arr.toString().split(',').map(item => +item);
console.log(newArr);

// reduce 遞歸寫法
let flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , []) : [arr];
newArr = flattenDeep(arr);
console.log(newArr);           

複制

數組的深拷貝

// Array.from()
var arr1 = [1,2,3];
var arr2 = Array.from(arr1);
// 數組尾部添加
arr2.push(100);
console.log(arr1,arr2); // [1, 2, 3] [1, 2, 3, 100]

// [...arr] 使用這個也可以拼接數組,但是不推薦,效率太低
var arr1 = [1,2,3];
// 超引用拷貝數組
var arr2 = [...arr1];
// 數組尾部添加
arr2.push(1000);
console.log(arr1,arr2); // [1, 2, 3] [1, 2, 3, 1000]

function show(...args){
// 此時這個形式參數就是一個數組,我們可以直接push東西進來,如下
args.push(5);
console.log(args);
}
// 調用
show(1,2,3,4); // [1, 2, 3, 4, 5]           

複制

部落格位址:https://ainyi.com/19