Skip to content

Instantly share code, notes, and snippets.

@veggiemonk
Last active December 13, 2015 13:50
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 veggiemonk/cb366de17a829289e16f to your computer and use it in GitHub Desktop.
Save veggiemonk/cb366de17a829289e16f to your computer and use it in GitHub Desktop.

FlattenDeep

This module can be used to flatten a deeply nested array.

Example

Deeply nested array

import flattenDeep from 'flattenDeep'

flattenDeep([[1,2,[3]],[4,[5,[],[6,[7]]]],[8,[9,10]]]) //-> [1,2,3,4,5,6,7,8,9,10]

Empty array and other values

flattenDeep([]) //-> []

//empty nested array are discarded
flattenDeep([1,[[],2]]) //-> [1,2]

flattenDeep('a') //-> 'a'

flattenDeep(undefined) //-> undefined
/** @module flattenDeep */
const isArray = Array.isArray
/**
* Flatten a deeply nested array
* @param {Array} nested - the array to flatten
* @return {*|Array} The flattened array or the argument if it is not an array
*/
const flattenDeep = (nested) => {
return !isArray(nested) ?
nested : //base case, single element
nested.reduce((acc, el) => { //flatten array
return isArray(el) ?
acc.concat(flattenDeep(el)) : //recurse
acc.concat(el)
}, [] )
}
export default flattenDeep
import { expect } from 'chai'
suite('Flatten a deeply nested array', () => {
test('deeply nested array', (done) => {
const result = flattenDeep([[1,2,[3]],[4,[5,[],[6,[7]]]],[8,[9,10]]]) //-> [1,2,3,4,5,6,7,8,9,10]
const expectedResult = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expect(result).to.deep.equal(expectedResult)
done()
})
test('empty array', (done) => {
expect(flattenDeep([])).to.equal([])
done()
})
test('empty nested array', (done) => {
expect(flattenDeep([[[]]])).to.equal([])
done()
})
test('empty nested array are discarded', (done) => {
expect(flattenDeep([1,[[],2]]))).to.deep.equal([1,2])
})
test('undefined', (done) => {
expect(flattenDeep(undefined)).to.equal(undefined))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment