Last active
July 5, 2018 18:05
-
-
Save krzystof/f0566b6c62bdc33d708d7889f132953d to your computer and use it in GitHub Desktop.
Flatten an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nestedArray = [[1,2,[3]],4] | |
const flattened = flatten(nestedArray) | |
const expected = [1, 2, 3, 4] | |
/** | |
* Because I didn't want to pull in a test framework | |
* for this case, I am just writing a custom assertion | |
* to verify that the array is flattened as expected. | |
*/ | |
if (!arraysEqual(expected, flattened)) { | |
console.log('Failed asserting that these 2 arrays are identicals: ', expected, flattened) | |
throw Error() | |
} else { | |
console.log('It is flattened') | |
} | |
/** | |
* Reduce the array recursively into a flat array. | |
*/ | |
function flatten(arr) { | |
return arr.reduce((flattened, item) => { | |
const other = item instanceof Array ? flatten(item) : [item] | |
return [...flattened, ...other] | |
}, []) | |
} | |
/** | |
* Compare two arrays with strict comparison | |
* of all the items. | |
*/ | |
function arraysEqual(first, second) { | |
if(first.length !== second.length) { | |
return false | |
} | |
for(let i = first.length; i--;) { | |
if(first[i] !== second[i]) | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment