Skip to content

Instantly share code, notes, and snippets.

@slacktracer
Created April 8, 2017 20:16
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 slacktracer/13f90ee415ea16fac3700f8c44a9f9f4 to your computer and use it in GitHub Desktop.
Save slacktracer/13f90ee415ea16fac3700f8c44a9f9f4 to your computer and use it in GitHub Desktop.
const flatten = function flatten(array) {
const flattened = array.reduce(
function reducer(reduced, arrayItem) {
const arrayItemIsArray = Array.isArray(arrayItem);
if (arrayItemIsArray) return reduced.concat(flatten(arrayItem));
return reduced.concat(arrayItem);
},
[]
);
return flattened;
}
const test = function test() {
const x = [[1,2,[3]],4];
const expected = '1,2,3,4';
const flattened = flatten(x);
if (flattened.toString() === expected) {
console.log('OK!');
} else {
console.error(`FAIL! Expected ${expected}. Got ${flattened.toString()}.`);
}
return flatten(x);
}
@slacktracer
Copy link
Author

On Node:

.load flatten.js

Then:

test();

Then:

PROFIT!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment