1

I have a deep array, hence the array with arrays children like below:

const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];

I wanna set all end children in a flat array, I use spread operator of ES6 but it spread shallow, I have no idea to how to make them to below:

const shallowArray = ['1','a','b',2,'4',3,'c',5];

Maybe a recursive function can do it but how? it should be very optimized because I wanna use it in a react native project. I'm worried about crash so I'm very cautious about optimization.

AmerllicA
  • 15,720
  • 11
  • 72
  • 103

3 Answers3

3

Use Array.prototype.flat to flatten the array, then use the spread operator as needed.

If you know the arrays depth or max size of depth, use the following code:

const flatArray = deepArray.flat(7); // assume you know depth size is 7

If you don't know the depth, you can use a recursive method that using reduce function, use below:

 const deepFlatten = arr =>
         arr.reduce(
           (acc, val) =>
             Array.isArray(val) 
               ? acc.concat(deepFlatten(val)) 
               : acc.concat(val),
             []
         );

Use above function to flat undeterminate depth:

const flatArray = deepFlatten(deepArray);
AmerllicA
  • 15,720
  • 11
  • 72
  • 103
Peter Van Drunen
  • 533
  • 5
  • 13
3

Using recursion, its pretty straightforward :)

let deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];
let array = [];
 
function f(d){
    Array.isArray(d)? d.forEach(x=> f(x)) : array.push(d);   
}
    
deepArray.forEach(x=>f(x));
console.log(array);    
    
Harunur Rashid
  • 3,825
  • 1
  • 16
  • 18
0

I want a flatten function for react-native merge styles. because in react-native sometimes you have a deep array of styles and it is essential to flat them.

But I find out the react-native StyleSheet have a good and optimized flatten function for handling this problem.

If someone read my question and need to handle deep arrays of style use below code:

const styleJoiner = (...arg) => StyleSheet.flatten(arg);
AmerllicA
  • 15,720
  • 11
  • 72
  • 103