Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Created January 30, 2019 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.
Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.
/**
* 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'}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment