JS array flattening (Flat)

Demand : multidimensional array => one-dimensional arrays

let ary = [1, [2, [3, [4, 5]]], 6];
let str = JSON.stringify(ary);

0 treatments: Direct call

arr_flat = arr.flat(Infinity);

The first treatment

ary = str.replace(/(\[\]))/g, '').split(',');

The second treatment

str = str.replace(/(\[\]))/g, '');
str = '[' + str + "]";
ary = JSON.parse(str);

The third process: a recursive process

let result = [];
let fn = function(ary) {
for(let i = 0; i < ary.length; i++) }{
let item = ary[i];
if (Array.isArray(ary[i])){
fn(item);
} else {
result.push(item);
}
}
}

The fourth process: implemented with the flat array of methods reduce

function flatten(ary) {
return ary.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
})
}
let ary = [1, 2, [3, 4], [5, [6, 7]]]
console.log(ary.MyFlat(Infinity))

Fifth process: Extended operator

while (ary.some(Array.isArray)) {
ary = [].concat(...ary);
}

Guess you like

Origin www.cnblogs.com/web-chuanfa/p/11681911.html