Skip to content

Instantly share code, notes, and snippets.

@mnlsn
Created March 6, 2020 08:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mnlsn/b0ac579268618df9e33a3a049711b1ac to your computer and use it in GitHub Desktop.
Flatten Array
/*
* This function flattens nested arrays
* @param {number[]}
* @param {number}
*
* @example
*
* flattenArray([[1,2,[3]],4], 4)
*
* @return {number[]}
*/
function flattenArray(array, depth = 100) {
if (!array || !Array.isArray(array)) {
console.warn(
"flattenArray: no array argument or array argument passed is not an array"
);
return false;
}
const flatArray = [];
let currentDepth = 0;
const flatten = arr => {
if (currentDepth === depth) {
return false;
}
currentDepth++;
for (let i = 0; i < arr.length; i++) {
const val = arr[i];
if (Array.isArray(val)) {
flatten(val);
} else {
flatArray.push(val);
}
}
};
flatten(array);
return flatArray;
}
module.exports = flattenArray;
const flattenArray = require("./flattenArray");
const testArray = [
1,
4,
3,
56,
667,
4324,
2,
6,
[9, 4, 55],
[92, 85, 20, 40],
5,
10
];
const deeperArray = [3, 34, 50, [72, 60, [testArray]]];
const expectedArray = [
1,
4,
3,
56,
667,
4324,
2,
6,
9,
4,
55,
92,
85,
20,
40,
5,
10
];
const example = [[1, 2, [3]], 4];
const expectedExample = [1, 2, 3, 4];
const expectedDepth1 = [3, 34, 50];
const expectedDepth2 = [3, 34, 50, 72, 60];
describe("flattenArray", () => {
test("returns flattened array", () => {
expect(flattenArray(testArray)).toStrictEqual(expectedArray);
});
test("returns only 1 level deep flattened array", () => {
expect(flattenArray(deeperArray, 1)).toStrictEqual(expectedDepth1);
});
test("returns only 2 levels deep flattened array", () => {
expect(flattenArray(deeperArray, 2)).toStrictEqual(expectedDepth2);
});
test("example given", () => {
expect(flattenArray(example, 3)).toStrictEqual(expectedExample);
});
});
{
"name": "flatten-array",
"version": "1.0.0",
"description": "",
"main": "flattenArray.js",
"scripts": {
"test": "npx jest flattenArray.test.js"
},
"author": "Mike Nelson",
"license": "MIT",
"devDependencies": {
"jest": "^25.1.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment