Skip to content

Instantly share code, notes, and snippets.

@supercamilo
Created October 23, 2017 16:50
Show Gist options
  • Save supercamilo/e30799e2d3e02dabc20e2d4950cf8a35 to your computer and use it in GitHub Desktop.
Save supercamilo/e30799e2d3e02dabc20e2d4950cf8a35 to your computer and use it in GitHub Desktop.
// flattens an array of arbitrarily nested arrays of integers into a flat array of integers
const flatten = (values) => values.reduce(
// concat single values and recursively flatten any nested arrays
(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []
);
export default flatten;
import flatten from './flatten';
it('flattens an array of arbitrarily nested arrays of integers into a flat array of integers', async () => {
const arr = [[1,2,[3]],4];
const flatArr = flatten(arr);
const innerArrs = flatArr.filter((item) => Array.isArray(item));
expect(innerArrs.length).toBeLessThan(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment