Last active
November 1, 2018 22:42
-
-
Save kevinchappell/ae6eb3c8759f00e39120aa065447da6d to your computer and use it in GitHub Desktop.
flattenArray code sample - https://codesandbox.io/s/jp5y2k71m3
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
/** | |
* recursively flatten a nested array | |
* @param {Array} arr to be flattened | |
* @return {Array} flattened array | |
*/ | |
const flattenArray = arr => | |
arr.reduce( | |
(acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val), | |
[] | |
); | |
module.exports = flattenArray; |
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
const flattenArray = require("./index"); | |
describe("flattenArray", () => { | |
it("should flatten an array", () => { | |
const nestedArray = [1, [2], 3]; | |
expect(flattenArray(nestedArray)).toEqual([1, 2, 3]); | |
}); | |
it("should flatten a deeply nested array", () => { | |
const nestedArray = [[1, 2, [3]], 4, [[[5]], 6]]; | |
expect(flattenArray(nestedArray)).toEqual([1, 2, 3, 4, 5, 6]); | |
}); | |
}); |
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
{ | |
"name": "citrus-byte-flatten-array", | |
"version": "0.0.1", | |
"description": "flattenArray code sample", | |
"main": "flattenArray.js", | |
"scripts": { | |
"test": "jest" | |
}, | |
"dependencies": {}, | |
"devDependencies": { | |
"jest": "23.6.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment