Array Flatten By Javascript

 

Note: doing test in vue cli 3.x enviroment

Method One: Recursion

flatFunc (arr) {
    arr.forEach((item, index) => {
        if(item.length && item.length >= 0) {
            this.flatFunc(item)
        } else {
            this.emptyArr.push(item)
        }
    })
    return this.emptyArr
}

Method Two:Extended Operator

flatFunc (arr) {
    arr.forEach((item, index) => {
        if(item.length && item.length >= 0) {
            this.emptyArr.push(...item)
        } else {
            this.emptyArr.push(item)
        }
    })
    return this.emptyArr
}

Method Three: Co-transformation Between Array and String

flatFunct (arr) {
    // Two methods you can use to transform array to string
    // let arrStr = arr.join(',')
    let arrStr = arr.toString()

    //Two method you can use to transform string to array
    // let newArr = arrStr.split(',').map(x => parseInt(x))
    // Two method you can use to transform a string number to a real number
    let newArr = arrStr.replace(/(\[\])/g, '').split(',').map(x => Number(x))
    return newArr
},

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章