js將多維陣列轉換為一維陣列

2022-06-22 11:39:16 字數 2434 閱讀 1376

解決方案有很多,以下來一一例舉

方法一:使用陣列的join()

let arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]]

console.log(arr.join()) // 輸出為:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16

let newarr = arr.join().split(',')

console.log(newarr) // 輸出為:["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]

方法二:使用tostring()方法

let arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]]

console.log(arr.tostring()) // 輸出為:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16

let newarr = arr.tostring().split(',')

console.log(newarr) // 輸出為:["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]

方法三: 使用空字串的方法

let arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]]

console.log(arr+ '') // 輸出為:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16

let newarr = (arr+ '').split(',')

console.log(newarr) // 輸出為:["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]

方法四:遞迴呼叫

let arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]]

let newarr = // 存放轉化後的一維陣列

function arrconversion (arr) else {

newarr.push(arr[i])

arrconversion(arr)

console.log(newarr) // 輸出為:["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]

es6寫法

const deepflatten = arr => .concat(...arr.map(v => (array.isarray(v) ? deepflatten(v) : v)));

deepflatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

方法五:flat()

console.log([1 ,[2, 3]].flat()); // [1, 2, 3]

// 指定轉換的巢狀層數

console.log([1, [2, [3, [4, 5]]]].flat(2)); // [1, 2, 3, [4, 5]]

// 不管巢狀多少層

console.log([1, [2, [3, [4, 5]]]].flat(infinity)); // [1, 2, 3, 4, 5]

// 自動跳過空位

console.log([1, [2, , 3]].flat());// [1, 2, 3]

方法六: 正則

let ary = [1, [2, [3, [4, 5]]], 6];

let str = json.stringify(ary);

let result = str.replace(/(\[|\])/g, '').split(',');

console.log(result)

方法七: 擴充套件運算子

let ary = [1, [2, [3, [4, 5]]], 6];// -> [1, 2, 3, 4, 5, 6]

//只要有乙個元素有陣列,那麼迴圈繼續

while (ary.some(array.isarray())) {

ary = .concat(...ary);

PHP 多維陣列轉換一維陣列

下面是我寫的將多維陣列轉換為一維陣列的類方法,轉換的一維陣列的每個元素包含了相應的值在原有多維陣列中的key,value以及維度 即深度 如果對應的原有元素也是陣列,則相應的一維元素的value則表示為 當然,這個可以改 在格式化輸出多維陣列的時候比較有效。class arrayhelper els...

JS多維陣列轉一維陣列

const arr 1 2 3 4 5,6 function flat array else return flata console.log flat arr 1,2,3,4,5,6 const arr 1 2 3 4 5,6 function flat a else const flatarr ...

一維陣列轉換為二維陣列

一維陣列 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 二維陣列 1,2,3,4,5 00,01,02,03,04 6,7,8,9,10 10,11,12,13,14 11,12,13,14,15 20,21,22,23,24 16,17,18...