Skip to content

Instantly share code, notes, and snippets.

@deltaepsilon
Created November 21, 2019 15:53
Show Gist options
  • Save deltaepsilon/04ecd3240666b7b770dbcbd6b1e4b036 to your computer and use it in GitHub Desktop.
Save deltaepsilon/04ecd3240666b7b770dbcbd6b1e4b036 to your computer and use it in GitHub Desktop.
Flatten
const flatten = require('./flatten');
describe('flatten', () => {
it('should flatten deeply nested arrays of integers', () => {
const arrays = [1, 2, 3, [4, 5, 6, [7, 8, 9], [10, 11, 12]]]
const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
expect(flatten(arrays)).toEqual(expected);
});
});
module.exports = function flatten(arrays) {
return arrays.reduce((acc, item) => {
const isArray = Array.isArray(item);
const newItems = isArray ? flatten(item) : [item];
return acc.concat(newItems);
}, [])
}
@deltaepsilon
Copy link
Author

deltaepsilon commented Nov 21, 2019

See a running implementation at https://repl.it/@Quiver/FlattenArrays

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment