Skip to content

Instantly share code, notes, and snippets.

@philcms1
Created March 16, 2019 12:26
Show Gist options
  • Save philcms1/2af5001fb598a4151647d1847db5e3b9 to your computer and use it in GitHub Desktop.
Save philcms1/2af5001fb598a4151647d1847db5e3b9 to your computer and use it in GitHub Desktop.
const flattenArr = (arr = []) => {
// Executing recursively a reducer function seems the logical choice, since it will result...
// ...in a single output value
return arr.reduce((accumulator, currentValue) => {
return accumulator.concat(Array.isArray(currentValue) ? flattenArr(currentValue) : currentValue);
}, []);
};
// Using Jest for testing
test('[[1,2,[3]],4] -> [1,2,3,4]', () => {
expect(flattenArr([[1,2,[3]],4])).toEqual([1,2,3,4]);
});
test('[] -> []', () => {
expect(flattenArr([])).toEqual([]);
});
test('undefined -> []]', () => {
expect(flattenArr()).toEqual([]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment