Skip to content

Instantly share code, notes, and snippets.

@arvinsim
Created March 6, 2017 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arvinsim/e9f53d0557f5b0a480d29cb5b5df673e to your computer and use it in GitHub Desktop.
Save arvinsim/e9f53d0557f5b0a480d29cb5b5df673e to your computer and use it in GitHub Desktop.
Code to flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
// NodeJS
const assert = require('assert');
/**
* Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
* e.g. [[1,2,[3]],4] -> [1,2,3,4].
*
* @name flatten
* @param {Array} arr An array to flatten, nested or otherwise
* @returns {Array} the flattened array
* @throws {Error}
*/
function flatten(arr) {
if (Array.isArray(arr)) {
return arr.reduce(function(acc, element) {
const items = Array.isArray(element) ? flatten(element) : [element];
return acc.concat(items);
}, []);
}
throw Error('Argument passed is not an array');
}
// Tests
function testFlatten() {
const testCase1 = flatten([[1, 2,], [3, 4], [5, 6]]);
const testCase2 = flatten([[1], 2, [3, 4], 5, 6]);
const testCase3 = flatten([[1, [2, [3, 4, [5, [6]]]]]]);
assert.deepEqual(testCase1, [1,2,3,4,5,6]);
assert.deepEqual(testCase2, [1,2,3,4,5,6]);
assert.deepEqual(testCase3, [1,2,3,4,5,6]);
}
testFlatten();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment