Skip to content

Instantly share code, notes, and snippets.

@frycz
Last active December 8, 2019 14:16
Show Gist options
  • Save frycz/5944c64f9c40b232b6345aef7445a2f3 to your computer and use it in GitHub Desktop.
Save frycz/5944c64f9c40b232b6345aef7445a2f3 to your computer and use it in GitHub Desktop.
Function flattens an array of arbitrarily nested arrays of integers into a flat array of integers
/**
* Flattens an array of arbitrarily nested arrays of integers into a flat array of integers.
* Run `jest ./flattenArray.test.js` for tests.
*
* @param {*} arr - nested array of integers
* @returns flattened array
*/
function flattenArray(arr) {
const result = [];
arr.forEach(elem => {
if (Array.isArray(elem)) {
result.push(...flattenArray(elem));
} else {
result.push(elem);
}
});
return result;
}
module.exports = flattenArray;
const flattenArray = require("./flattenArray");
describe("flattenArray", () => {
it("should map flat array to flat array", () => {
expect(flattenArray([])).toEqual([]);
expect(flattenArray([1, 2, 3])).toEqual([1, 2, 3]);
});
it("should flatten nested array to flat array", () => {
expect(flattenArray([1, 2, [3, 4, [5, 6, 7], 8, 9]])).toEqual([
1,
2,
3,
4,
5,
6,
7,
8,
9
]);
expect(flattenArray([1, 2, [], 3, [4, [], 5], 6])).toEqual([
1,
2,
3,
4,
5,
6
]);
});
});
module.exports = { verbose: true };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment