Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active August 6, 2017 23:41
Show Gist options
  • Save zeusdeux/75b991097839461f50a0 to your computer and use it in GitHub Desktop.
Save zeusdeux/75b991097839461f50a0 to your computer and use it in GitHub Desktop.
Flatten nested arrays
function flatten(arr) {
return arr.reduce(
(acc, c) => acc.concat(Array.isArray(c) ? flatten(c) : c),
[]
);
}
// to run, execute: node flatten.test.js
'use strict';
const assert = require('assert');
const flatten = require('./flatten');
const tests = [
[[1, 2], [1, 2]],
[[1, [2]], [1, 2]],
[[[1], 2], [1, 2]],
[[[[[[[1], 2]]]]], [1, 2]],
[[1, 2, 3, [[[[[4], 5]], 6], 7], 8], [1, 2, 3, 4, 5, 6, 7, 8]],
[[], []],
[[1], [1]],
[[[1]], [1]],
[[[[[[[[[1]]]]]]]], [1]]
];
const passedTests = tests.reduce(function(p, c, i) {
try {
assert.deepEqual(flatten(c[0]), c[1]);
}
catch(e) {
console.error('Something broke in test %d', i + 1);
throw e;
}
return ++p;
}, 0);
console.log('%d tests passed', passedTests);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment