Skip to content

Instantly share code, notes, and snippets.

@kevinchappell
Last active November 1, 2018 22:42
Show Gist options
  • Save kevinchappell/ae6eb3c8759f00e39120aa065447da6d to your computer and use it in GitHub Desktop.
Save kevinchappell/ae6eb3c8759f00e39120aa065447da6d to your computer and use it in GitHub Desktop.
flattenArray code sample - https://codesandbox.io/s/jp5y2k71m3
/**
* 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;
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]);
});
});
{
"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