Created
November 21, 2019 15:53
-
-
Save deltaepsilon/04ecd3240666b7b770dbcbd6b1e4b036 to your computer and use it in GitHub Desktop.
Flatten
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
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); | |
}); | |
}); |
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
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); | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See a running implementation at https://repl.it/@Quiver/FlattenArrays