Skip to content

Instantly share code, notes, and snippets.

@raspo
Last active May 24, 2016 00:56
Show Gist options
  • Save raspo/b599cff1169d7d21ed83ea5734dc1492 to your computer and use it in GitHub Desktop.
Save raspo/b599cff1169d7d21ed83ea5734dc1492 to your computer and use it in GitHub Desktop.
Flatten Array
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]);
});
});
// 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