Skip to content

Instantly share code, notes, and snippets.

@madroneropaulo
Created June 28, 2019 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madroneropaulo/af156a69308b6948b7e92392afa65595 to your computer and use it in GitHub Desktop.
Save madroneropaulo/af156a69308b6948b7e92392afa65595 to your computer and use it in GitHub Desktop.
Array Flattener
function flattenArray(nestedArray) {
const flatArr = [];
function flattenerFunc (arr) {
arr.forEach(el => {
if (Array.isArray(el)) {
flattenerFunc(el);
} else {
flatArr.push(el);
}
});
}
flattenerFunc(nestedArray);
return flatArr
}
module.exports = flattenArray;
const flattenArray = require("./flattener");
test('flattens integer array', () => {
const nestedArr = [0,[1,2,3,[4,[5]]],6,7];
const flatteredArr = flattenArray(nestedArr);
expect(flatteredArr).toEqual([0,1,2,3,4,5,6,7]);
});
test('flattens any array', () => {
const anyNestedArr = ['a', [0, undefined], {name: "hello"}, [false, 5, {hello: "world"}]];
const flatteredArr = flattenArray(anyNestedArr);
expect(flatteredArr).toEqual(['a', 0, undefined, {name: "hello"}, false, 5, {hello: "world"}]);
});
@madroneropaulo
Copy link
Author

Requires jest. Works not only with numbers, but with any type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment