Skip to content

Instantly share code, notes, and snippets.

@migreva
Last active July 4, 2019 02:25
Show Gist options
  • Save migreva/2053c443d8195ad4a5722046d45f486e to your computer and use it in GitHub Desktop.
Save migreva/2053c443d8195ad4a5722046d45f486e to your computer and use it in GitHub Desktop.
Flatten some arrays
/**
* Yo dawg I heard you like arrays, so if you put arrays in your
* arrays here's a function that can flatten it. O(n) complexity
*
* e.g flattenArray([[1,2,[3]],4]) -> [1,2,3,4]
*
* @param {Array} inputArray - Unflattened array
* @returns {Array} flattened array, bye bye pesky nested arrays
*/
function flattenArray(inputArray, outputArray = []) {
for (let i = 0; i < inputArray.length; i++) {
const inputValue = inputArray[i];
if (Array.isArray(inputValue)) flattenArray(inputValue, outputArray);
else outputArray.push(inputValue);
}
return outputArray;
}
function testFlatten() {
const flattenTestCases = [{
inputArray: [1],
expectedOutput: [1],
}, {
inputArray: [1, 2, 3, 4],
expectedOutput: [1, 2, 3, 4],
}, {
inputArray: [[1,2,[3]],4],
expectedOutput: [1, 2, 3, 4],
}, {
inputArray: [[1,[2],3],4],
expectedOutput: [1, 2, 3, 4],
}, {
inputArray: [[1,2,[3]],4, [6], [8, [9], 10], 11],
expectedOutput:  [1, 2, 3, 4, 6, 8, 9, 10, 11],
}]
for (let testCase of flattenTestCases) {
const outputArray = flattenArray(testCase.inputArray);
if (!areArraysEqual(outputArray, testCase.expectedOutput)) {
console.error(`Arrays are inequal:\n\n\tExpected: ${testCase.expectedOutput}\n\tActual: ${outputArray}`);
return;
}
}
console.log('flatten is humming long fine');
}
function areArraysEqual(arr1 = [], arr2 = []) {
// arrays cant be equal if their lengths aren't equal
if (arr1.length !== arr2.length) return false;
// compare each index in each array
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
// checks pass! arrays are equal
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment