Skip to content

Instantly share code, notes, and snippets.

@plrenaudin
Created May 11, 2019 12:05
Show Gist options
  • Save plrenaudin/c8cc61c95de5d721fc09481b3b2e4c9e to your computer and use it in GitHub Desktop.
Save plrenaudin/c8cc61c95de5d721fc09481b3b2e4c9e to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
/**
* Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
* @param {Array} arr The array of arbitrarily nested arrays of integers
* @returns {Array[number]} Flat array of integers
*/
const flatten = (arr = []) =>
arr.reduce((acc, val) => (Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val)), []);
it("works with no input", () => {
expect(flatten()).toEqual([]);
});
it("works with the example input", () => {
expect(flatten([[1, 2, [3]], 4])).toEqual([1, 2, 3, 4]);
});
it("works with empty nested array", () => {
expect(flatten([[1, 2, []], 4])).toEqual([1, 2, 4]);
});
it("works with multiple nested array", () => {
expect(flatten([1, 2, [[[3]]]])).toEqual([1, 2, 3]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment