-
-
Save 7flash/72359bc62977fb069efde01cab6393c7 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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