Last active
May 24, 2016 00:56
-
-
Save raspo/b599cff1169d7d21ed83ea5734dc1492 to your computer and use it in GitHub Desktop.
Flatten Array
This file contains hidden or 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
import { flatten } from 'utils'; | |
describe('flatten', () => { | |
it('flatten', () => { | |
expect(flatten([])).toEqual([]); | |
expect(flatten([[], []])).toEqual([]); | |
expect(flatten([[1, 2, [3]], 4])).toEqual([1, 2, 3, 4]); | |
expect(flatten([[1, 2, 3], [4, [5, 6, [7, [8]]]], 9])).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); | |
}); | |
}); |
This file contains hidden or 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
// flatten an array of arbitrarily nested arrays | |
export function flatten(array) { | |
if (!array.length) { return []; } | |
return array.reduce((prev, el) => { | |
if (Array.isArray(el)) { | |
return prev.concat(flatten(el)); | |
} | |
return prev.concat(el); | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment