Back to Freecodecamp

Challenge 171: Flatten the Array

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29d.md

latest1.7 KB
Original Source

--description--

Given an array that contains nested arrays, return a new array with all values flattened into a single, one-dimensional array. Retain the original order of the items in the arrays.

--hints--

flatten([1, [2, 3], 4]) should return [1, 2, 3, 4].

js
assert.deepEqual(flatten([1, [2, 3], 4]), [1, 2, 3, 4]);

flatten([5, [4, [3, 2]], 1]) should return [5, 4, 3, 2, 1].

js
assert.deepEqual(flatten([5, [4, [3, 2]], 1]), [5, 4, 3, 2, 1]);

flatten(["A", [[[["B"]]]], "C"]) should return ["A", "B", "C"].

js
assert.deepEqual(flatten(["A", [[[["B"]]]], "C"]), ["A", "B", "C"]);

flatten([["L", "M", "N"], ["O", ["P", "Q", ["R", ["S", ["T", "U"]]]]], "V", ["W", ["X", ["Y", ["Z"]]]]]) should return ["L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"].

js
assert.deepEqual(flatten([["L", "M", "N"], ["O", ["P", "Q", ["R", ["S", ["T", "U"]]]]], "V", ["W", ["X", ["Y", ["Z"]]]]]), ["L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]);

flatten([["red", ["blue", ["green", ["yellow", ["purple"]]]]], "orange", ["pink", ["brown"]]]) should return ["red","blue","green","yellow","purple","orange","pink","brown"].

js
assert.deepEqual(flatten([["red", ["blue", ["green", ["yellow", ["purple"]]]]], "orange", ["pink", ["brown"]]]), ["red","blue","green","yellow","purple","orange","pink","brown"]);

--seed--

--seed-contents--

js
function flatten(arr) {

  return arr;
}

--solutions--

js
function flatten(arr) {
  let result = [];

  for (const item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result.push(item);
    }
  }

  return result;
}