Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.