/ / the original array
let arr= [1[2[3.4[{a:5},'6']],7]].Copy the code

1. Use the array.prototype. flat method in ES6

arr.flat(Infinity);
Copy the code

2. Use reduce

function arrFlat(arr) {
    return arr.reduce((pre, cur) = > {
        return pre.concat(Array.isArray(cur) ? arrFlat(cur) : cur); }}, [])Copy the code

3. Use recursion and loop

function arrFlat(arr) {
    let result = [];
    arr.map((item, index) = > {
        if (Array.isArray(item)) {
            result = result.concat(arrFlat(item));
        } else{ result.push(item); }})return result;
}
Copy the code

or

let result = [];
function arrFlat(arr){
    for(const key of arr){
        if(Array.isArray(key)){
            return arrFlat(key);
        }else{ result.push(key); }}}Copy the code

4. Turn arrays into strings and undo toString()

(Only applicable to array elements that are all strings or numbers)

function arrFlat(arr) {
    return arr.toString().split(', ').map(item= >+item);
}
Copy the code