Skip to content

Instantly share code, notes, and snippets.

@corlaez
Last active December 19, 2019 15:17
Show Gist options
  • Save corlaez/e82a719b030ee422018461d21052f4a0 to your computer and use it in GitHub Desktop.
Save corlaez/e82a719b030ee422018461d21052f4a0 to your computer and use it in GitHub Desktop.
Flatten an Array!

Flatten an array.

Requirements

You will need node js to run this array flattener.

How to run

Open your terminal/cmd and execute:

npx https://gist.github.com/lrn2prgrm/e82a719b030ee422018461d21052f4a0
#!/usr/bin/env node
/* Returns a new array that is a flattened version of the param */
function flatten(array){
const accumulatorArray = []
return array.reduce(flattenReducer, accumulatorArray);
}
/* A recursive reducer that will push all the elements into the accumulator array */
function flattenReducer(array, e) {
const eIsAnArray = e != null && e.constructor.name === 'Array';
if (eIsAnArray) {
e.reduce(flattenReducer, array);
} else {
array.push(e);
}
return array
}
function testFlatten(array, expectedArrayString) {
console.log('try ' + JSON.stringify(array));
console.log('flattening...');
const newArray = JSON.stringify(flatten(array));
if (newArray !== expectedArrayString) {
throw Error('Expected ' + expectedArrayString + ' but recieved ' + newArray)
}
console.log(newArray);
}
testFlatten([[[[[[[1]]]]]]], "[1]")
testFlatten([[[[[[[1]]]]]],2], "[1,2]")
testFlatten([[1,2],3,4,[[[[5],6,[7],[[8,9]]]]]], "[1,2,3,4,5,6,7,8,9]")
{
"name": "npx-flatten",
"version": "0.0.1",
"bin": "./index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment