Flatten nested arrays in java

前端 未结 6 665
失恋的感觉
失恋的感觉 2020-12-01 13:32

I want to flatten nested arrays like:

[[[1],2],[3]],4] -> [1,2,3,4] 

manually in java I can\'t find a clue ! :S

I have tried a

6条回答
  •  青春惊慌失措
    2020-12-01 14:08

    That's the way I would solve it. Don't know which kind of efficiency you are looking for. But yeah. that does the job in JavaScript.

    arr.toString().split(',').filter((item) => item).map((item) => Number(item))

    A probably more efficient way to do this would be to use reduce and concat method from arr and recursion.

    function flattenDeep(arr1) {
       return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
    }
    

提交回复
热议问题