Skip to content

Instantly share code, notes, and snippets.

@brianscroggins24
Last active October 25, 2016 14:50
Show Gist options
  • Select an option

  • Save brianscroggins24/657df693230e4e38948f126b4514c167 to your computer and use it in GitHub Desktop.

Select an option

Save brianscroggins24/657df693230e4e38948f126b4514c167 to your computer and use it in GitHub Desktop.

Revisions

  1. brianscroggins24 revised this gist Oct 25, 2016. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions flattenRecursive.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,8 @@
    /*
    Example of a flatten array method using recursion. If the original array is
    large do NOT use this funtion. Too much memory is used off the stack.
    */

    let array = [[1,2,[3]],4];
    let newArray = flattenRecursive(array);

  2. brianscroggins24 revised this gist Oct 25, 2016. No changes.
  3. brianscroggins24 created this gist Oct 25, 2016.
    13 changes: 13 additions & 0 deletions flattenRecursive.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    let array = [[1,2,[3]],4];
    let newArray = flattenRecursive(array);

    function flattenRecursive(array, results = []) {
    for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
    flattenRecursive(array[i], results); // called until the inner most array is reached
    } else {
    results.push(array[i]);
    }
    }
    return results;
    }