Skip to content

Instantly share code, notes, and snippets.

@krzystof
Last active July 5, 2018 18:05
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 krzystof/f0566b6c62bdc33d708d7889f132953d to your computer and use it in GitHub Desktop.
Save krzystof/f0566b6c62bdc33d708d7889f132953d to your computer and use it in GitHub Desktop.
Flatten an array
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