Skip to content

Instantly share code, notes, and snippets.

@Pau1fitz
Created September 22, 2019 09:17
Show Gist options
  • Save Pau1fitz/cf4d05b9119c3ea838f0fb31805f10f4 to your computer and use it in GitHub Desktop.
Save Pau1fitz/cf4d05b9119c3ea838f0fb31805f10f4 to your computer and use it in GitHub Desktop.
Flatten multi-dimensional array
const flatten = (arr) => arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
const multiDimensionalArray = [[1,2,[3]],4];
const flattenedArray = flatten(multiDimensionalArray);
it('flattens an array of arbitrarily nested arrays of integers into a flat array of integers', () => {
assert.equal(flatten([[1,2,[3]],4]), [1, 2, 3, 4])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment