Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Takes an array of arbitrary depth
- // Returns a flattened array of all @array's elements
- const arrayFlatten = (array) => {
- let flattened = [...array];
- while (flattened.some(el => Array.isArray(el))) {
- flattened = flattened.reduce((arr, el) => arr.concat(el), []);
- }
- return flattened;
- }
- // Example mocha tests
- describe('arrayFlatten()', () => {
- it('returns unmodified array if already flat', () => {
- const array = [1,2,3,4,5,6];
- expect(arrayFlatten(array)).to.deep.equal(array);
- });
- it('flattens a 2D array of numbers', () => {
- const array2D = [[1,2],[3,4],[5,6]];
- const flattened = [1,2,3,4,5,6];
- expect(arrayFlatten(array2D)).to.deep.equal(flattened);
- });
- it('flattens an array of arbitrary depth', () => {
- const deepArray = [[[[1,2,[3,4,[5,6],7],8],9,[10,11],12,13],[14,15]],16,17];
- const flattened = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
- expect(arrayFlatten(deepArray)).to.deep.equal(flattened);
- });
- it('does not directly mutate the passed-in array', () => {
- const array = [[1,2],[3,4],[5,6]];
- const array2 = [[1,2],[3,4],[5,6]];
- arrayFlatten(array);
- expect(array).to.deep.equal(array2);
- })
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement