current position:Home>Front end array flattening

Front end array flattening

2022-06-24 09:43:28You are far from it.

1. The first one is

		let arr = [1, 2, 3, [4, 5, [6, 7, 8]]]
        console.log(arr.flat(Infinity));

2. The second kind

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

3. The third kind of

   		let arr = [1, 2, 3, [4, 5, [6, 7, 8]]]
        let brr = []
        function fn(arr) {
    
            arr.forEach((v) => {
    
                if (typeof v === "object") {
    
                    fn(v)
                } else {
    
                    brr.push(v)
                }
            })
            return brr
        }
        console.log(fn(arr));

copyright notice
author[You are far from it.],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240824353617.html

Random recommended