Skip to content

Instantly share code, notes, and snippets.

@codenamezjames
Created January 1, 2019 16:15

Revisions

  1. codenamezjames created this gist Jan 1, 2019.
    28 changes: 28 additions & 0 deletions flatten.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    function flatten(arr, depth = Infinity, result = []) {
    if(!Array.isArray(arr)) return null
    for (const value of arr) {
    if (depth > 0 && Array.isArray(value)) {
    if (depth > 1) {
    flatten(value, depth - 1, result)
    } else {
    result.push(...value)
    }
    } else {
    result[result.length] = value
    }
    }
    return result
    }


    // Tests
    const superFlat = JSON.stringify(flatten( [[ [[[[1]]]], 2, [ 3 ] ], 4] )) === JSON.stringify([1, 2, 3, 4])
    if ( !superFlat ) throw 'Failed to flatten many layers deep'

    const oneLayer = JSON.stringify(flatten( [1,2,3,[[4]]], 1 )) === JSON.stringify([1,2,3,[4]])
    if (!oneLayer) throw 'Failed to only flatten one layer'

    const crazyInput = JSON.stringify(flatten( {1:1, 2:2, 3:3} )) === JSON.stringify(null)
    if(!crazyInput) throw 'Does not handle crazy inputs'

    console.log('Everything flattened successfully')