Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Created January 30, 2019 15:35
Show Gist options
  • Select an option

  • Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.

Select an option

Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.

Revisions

  1. ksafranski created this gist Jan 30, 2019.
    17 changes: 17 additions & 0 deletions flatDeep.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    /**
    * Function for converting arbitrarily nested arrays into a single, flat array
    * @param {Array} arr
    * @returns {Array}
    */
    function flatDeep (arr) {
    if (!Array.isArray(arr)) throw new Error('Expected type `Array`')
    return arr.reduce((acc, el) => acc.concat(Array.isArray(el) ? flatDeep(el) : el), [])
    }

    // Tests
    const assert = require('assert')
    assert.throws(() => flatDeep('foo'), Error)
    assert.deepEqual(flatDeep([[1,2,[3]],4]), [1, 2, 3, 4])
    assert.deepEqual(flatDeep([1,,3,[4]]), [1,3,4])
    assert.deepEqual(flatDeep([1, ['foo', true]]), [1,'foo',true])
    assert.deepEqual(flatDeep([[1], [{ foo: 'bar' }]]), [1,{foo: 'bar'}])