Fix the Array Flattening Function
MediumChallenge 9 of 20
Fix the Array Flattening Function
MediumThis function is supposed to flatten a nested array, but it doesn't handle all cases correctly. Fix the implementation.
Challenge 9 of 20
50 XP
Community Solutions
ArraysRecursionData StructuresJavaScript
Exit ChallengeTest Cases
0/3 passingTest Case #1
Input: flattenArray([1, [2, 3], 4])
Expected: [1, 2, 3, 4]
Run tests to see results
Test Case #2
Input: flattenArray([1, [2, [3, 4], 5], 6])
Expected: [1, 2, 3, 4, 5, 6]
Run tests to see results
Test Case #3
Input: flattenArray([1, 2, 3])
Expected: [1, 2, 3]
Run tests to see results
solution.js
1
<span class="token keyword">function</span> flattenArray(arr) {
<span class="token keyword">let</span> result = [];
<span class="token keyword">for</span> (<span class="token keyword">let</span> i = <span <span class="token keyword">class</span>="token number">0</span>; i < arr.length; i++) {
<span class="token keyword">if</span> (Array.isArray(arr[i])) {
result = result.concat(arr[i]);
} <span class="token keyword">else</span> {
result.push(arr[i]);
}
}
<span class="token keyword">return</span> result;
}Console
Run your code to see output here