Last active
August 25, 2020 06:11
-
-
Save abmohan/e32001c9009c3bd35c5ff9a3a0594605 to your computer and use it in GitHub Desktop.
Flattening An Array of Arbitrarily Nested Arrays
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
/** | |
* Flattens an array of arbitrarily nested arrays | |
* @param {Array} sourceArray [array of arbitrarily nested arrays] | |
* @return {Array} [flattened array] | |
*/ | |
function flatten(sourceArray) { | |
return sourceArray.reduce( | |
(flattenedArray, currentArrayElement) => { | |
// append current array element to end of array | |
return flattenedArray.concat( | |
Array.isArray(currentArrayElement) ? | |
flatten(currentArrayElement) : // recursively flatten, if necessary | |
currentArrayElement | |
); | |
}, | |
[] // initialize to empty array | |
); | |
} | |
module.exports = flatten; |
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
/* | |
* Simple test cases to provide a sanity check | |
* using assert (rather than mocha+chai or jasmine), for simplicity | |
*/ | |
const assert = require('assert'); | |
const flatten = require('./flatten'); | |
const testCases = [ | |
{ | |
test: [1], | |
expected: [1] | |
}, | |
{ | |
test: [[1]], | |
expected: [1] | |
}, | |
{ | |
test: [[[[[1]]]]], | |
expected: [1] | |
}, | |
{ | |
test: [1, 2, 3, 4], | |
expected: [1, 2, 3, 4] | |
}, | |
{ | |
test: [[1, 2, [3]], 4], | |
expected: [1, 2, 3, 4] | |
}, | |
{ | |
test: [[[1, 2], [3]], 4], | |
expected: [1, 2, 3, 4] | |
}, | |
{ | |
test: [[[[[[1]]]]], 2, 3, 4], | |
expected: [1, 2, 3, 4] | |
}, | |
{ | |
test: [], | |
expected: [] | |
}, | |
{ | |
test: [[]], | |
expected: [] | |
}, | |
{ | |
test: [[], []], | |
expected: [] | |
} | |
]; | |
testCases.forEach(testCase => { | |
const actual = flatten(testCase.test); | |
assert.equal(JSON.stringify(testCase.expected), JSON.stringify(actual)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment