Thursday, July 23, 2020

Steamroller

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

Intermediate Algorithm Scripting: Steamroller

Flatten a nested array. You must account for varying levels of nesting.


const steamrollArray = arr => 
    arr.reduce((acc, el) => acc.concat(Array.isArray(el) ? steamrollArray(el) : el), []);
    
[
  steamrollArray([[["a"]], [["b"]]]),
  steamrollArray([1, [2], [3, [[4]]]]),
  steamrollArray([1, [], [3, [[4]]]]),
  steamrollArray([1, {}, [3, [[4]]]]) 
].forEach(result => console.log(result));

Output:
[ 'a', 'b' ]
[ 1, 2, 3, 4 ]
[ 1, 3, 4 ]
[ 1, {}, 3, 4 ]

No comments:

Post a Comment