Created
May 11, 2019 12:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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