-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithms16.html
50 lines (39 loc) · 1.16 KB
/
algorithms16.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller
//Flatten a nested array. You must account for varying levels of nesting.
//solution #1
// function steamrollArray(arr) {
// var newArr =[];
// for (var i=0; i<arr.length; i++) {
// if (Array.isArray(arr[i])){
// //use recursion to flatten the sub-array
// newArr.push(...steamrollArray(arr[i]));
// } else {
// newArr.push(arr[i]);
// }
// }
// return newArr;
// }
// solution #2
function steamrollArray(arr){
return arr.map(e=> {
if (Array.isArray(e)){
return steamrollArray(e);
} else {
return [e];
}
}).reduce((a,b)=>a.concat(b), []);
}
//tests
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([[["a"]], [["b"]]]));
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([[1, [], [3, [[4]]]]]));
console.log(steamrollArray([[1, [], [3, [[4]]]]]));
console.log(steamrollArray([1, {}, [3, [[4]]]]));
</script>
</body>
</html>