Created
January 30, 2019 15:35
-
-
Save ksafranski/e7c6165c333b17c1cf9f055edc4b778e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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