freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../intermediate-algorithm-scri.../steamroller.md

72 lines
1.3 KiB
Markdown
Raw Normal View History

---
id: ab306dbdcc907c7ddfc30830
title: Steamroller
challengeType: 5
forumTopicId: 16079
---
# --description--
Flatten a nested array. You must account for varying levels of nesting.
# --hints--
`steamrollArray([[["a"]], [["b"]]])` should return `["a", "b"]`.
```js
assert.deepEqual(steamrollArray([[['a']], [['b']]]), ['a', 'b']);
```
`steamrollArray([1, [2], [3, [[4]]]])` should return `[1, 2, 3, 4]`.
```js
assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
```
`steamrollArray([1, [], [3, [[4]]]])` should return `[1, 3, 4]`.
```js
assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
```
`steamrollArray([1, {}, [3, [[4]]]])` should return `[1, {}, 3, 4]`.
```js
assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
```
Your solution should not use the `Array.prototype.flat()` or `Array.prototype.flatMap()` methods.
```js
assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/));
```
# --seed--
## --seed-contents--
```js
function steamrollArray(arr) {
return arr;
}
steamrollArray([1, [2], [3, [[4]]]]);
```
# --solutions--
```js
function steamrollArray(arr) {
if (!Array.isArray(arr)) {
return [arr];
}
var out = [];
arr.forEach(function(e) {
steamrollArray(e).forEach(function(v) {
out.push(v);
});
});
return out;
}
```