Last active
October 23, 2019 21:13
-
-
Save felipediogo/dc9c7ba00130a1d7ed9ddd7edd0ced89 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
It does a reduce, where it will test if each item is an array, | |
if it is it will call the function recursively, | |
it's possible only because of array.concat which will merge arrays together. | |
or you could use the spread sintax to merge them together IE: [...acc, ...flatten(item)], | |
but I think this way it's a little more readble. | |
*/ | |
const flatten = arrays => arrays.reduce((acc, item) => Array.isArray(item) ? acc.concat(flatten(item)) : acc.concat(item), []); | |
describe('Flatten arrays', () => { | |
it('should flatten [1,2,3,[4,5,6, [7,8,9]],10,[11,[12],13]], to [1,2,3,4,5,6,7,8,9,10,11,12,13]', () => { | |
const input = [1,2,3,[4,5,6, [7,8,9]],10,[11,[12],13]]; | |
const result = [1,2,3,4,5,6,7,8,9,10,11,12,13]; | |
expect(flatten(input)).toEqual(result) | |
}); | |
it('should ignore empty spaces [1,2,3,[4,[], 5,6, [[[[[],[],[]]]]]], [7,8,9]], to [1,2,3,4,5,6,7,8,9]', () => { | |
const input = [1,2,3,[4,[], 5,6, [[[[[],[],[]]]]], [7,8,9]]]; | |
const result = [1,2,3,4,5,6,7,8,9]; | |
expect(flatten(input)).toEqual(result) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment