Skip to content

Instantly share code, notes, and snippets.

@aaronroberson
Last active September 23, 2017 00:43
Show Gist options
  • Select an option

  • Save aaronroberson/42db0ccd06d5aac8692ffef150e8b9d0 to your computer and use it in GitHub Desktop.

Select an option

Save aaronroberson/42db0ccd06d5aac8692ffef150e8b9d0 to your computer and use it in GitHub Desktop.

Revisions

  1. aaronroberson revised this gist Sep 23, 2017. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions flatten-nested-array.js
    Original file line number Diff line number Diff line change
    @@ -5,17 +5,18 @@
    * @returns {Array} - The flattened array, yay!
    */
    function flattenNested(value, iterator = []) {
    // Add exit case straight away to help prevent stack overflow
    if (!value) return iterator;

    // Ensure that the value is an array before calling prototype methods on it
    value.forEach(item => {
    for (item of value) {
    if (Array.isArray(item)) {
    // Flatten nested array using recursion
    flattenNested(item, iterator);
    } else {
    // Push the item onto the iterator
    iterator.push(item);
    }
    });
    };
    return iterator;
    }
  2. aaronroberson created this gist Sep 21, 2017.
    21 changes: 21 additions & 0 deletions flatten-nested-array.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    /**
    * flattenNested - Reduces an array of arbitrarily nested arrays of integers into a flat array of integers.
    * @param value {Array} - The array to flatten.
    * @param iterator {Array} - An array used for initializing or for iteration during recursion.
    * @returns {Array} - The flattened array, yay!
    */
    function flattenNested(value, iterator = []) {
    if (!value) return iterator;

    // Ensure that the value is an array before calling prototype methods on it
    value.forEach(item => {
    if (Array.isArray(item)) {
    // Flatten nested array using recursion
    flattenNested(item, iterator);
    } else {
    // Push the item onto the iterator
    iterator.push(item);
    }
    });
    return iterator;
    }