Adding short and clear solution

This commit is contained in:
VitBu
2018-10-19 18:03:25 +03:00
committed by Kristofer Koishigawa
parent e3fe801288
commit 62ba0777e0

View File

@ -100,6 +100,29 @@ You will definitely need recursion or another way to go beyond two level arrays
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator' target='_blank' rel='nofollow'>Spread operator</a> * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator' target='_blank' rel='nofollow'>Spread operator</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator' target='_blank' rel='nofollow'>Ternary Operator (`condition ? a : b`)</a> * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator' target='_blank' rel='nofollow'>Ternary Operator (`condition ? a : b`)</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution 2:
function steamrollArray(arr) {
while(arr.some(element => Array.isArray(element))) {
arr = arr.flat();
}
return arr;
}
steamrollArray([1, [2], [3, [[4]]]]);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/repls/ContentMiserlySweepsoftware' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Use `Array.some()` method to find out if the new array contains an array still, if it does flatten the array
* Repeats, until there is no more arrays inside arr.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some' target='_blank' rel='nofollow'>Array.some</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat' target='_blank' rel='nofollow'>Array.flat</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: ## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
function steamrollArray(arr) { function steamrollArray(arr) {