Skip to content

Instantly share code, notes, and snippets.

@felipediogo
Last active October 23, 2019 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipediogo/dc9c7ba00130a1d7ed9ddd7edd0ced89 to your computer and use it in GitHub Desktop.
Save felipediogo/dc9c7ba00130a1d7ed9ddd7edd0ced89 to your computer and use it in GitHub Desktop.
/*
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