Hassaan Pasha d89eae392f
fix: adding test to check if flat or flatMap method was used in the steamroller challenge (#38158)
* fix: adding test to check if flat or flatMap method was used in the steamroller challenge

* Addressed comments and acknowledged suggestions
2020-02-04 17:00:33 -05:00

2.0 KiB

id, title, isRequired, challengeType, forumTopicId
id title isRequired challengeType forumTopicId
ab306dbdcc907c7ddfc30830 Steamroller true 5 16079

Description

Flatten a nested array. You must account for varying levels of nesting. Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.

Instructions

Tests

tests:
  - text: <code>steamrollArray([[["a"]], [["b"]]])</code> should return <code>["a", "b"]</code>.
    testString: assert.deepEqual(steamrollArray([[["a"]], [["b"]]]), ["a", "b"]);
  - text: <code>steamrollArray([1, [2], [3, [[4]]]])</code> should return <code>[1, 2, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
  - text: <code>steamrollArray([1, [], [3, [[4]]]])</code> should return <code>[1, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
  - text: <code>steamrollArray([1, {}, [3, [[4]]]])</code> should return <code>[1, {}, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
  - text: Your solution should not use the <code>Array.prototype.flat()</code> or <code>Array.prototype.flatMap()</code> methods.
    testString: assert(!code.match(/\.flat\([\s\S]*?\)/) && !code.match(/\.flatMap\([\s\S]*?\)/));

Challenge Seed

function steamrollArray(arr) {
  // I'm a steamroller, baby
  return arr;
}

steamrollArray([1, [2], [3, [[4]]]]);

Solution

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;
}