Adding short and clear solution
This commit is contained in:
committed by
Kristofer Koishigawa
parent
e3fe801288
commit
62ba0777e0
@ -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/Conditional_Operator' target='_blank' rel='nofollow'>Ternary Operator (`condition ? a : b`)</a>
|
||||
|
||||
##  Intermediate Code Solution 2:
|
||||
|
||||
function steamrollArray(arr) {
|
||||
while(arr.some(element => Array.isArray(element))) {
|
||||
arr = arr.flat();
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
steamrollArray([1, [2], [3, [[4]]]]);
|
||||
|
||||
 <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>
|
||||
|
||||
##  Advanced Code Solution:
|
||||
|
||||
function steamrollArray(arr) {
|
||||
|
Reference in New Issue
Block a user