Skip to content

Instantly share code, notes, and snippets.

@abmohan
Last active August 25, 2020 06:11
Show Gist options
  • Save abmohan/e32001c9009c3bd35c5ff9a3a0594605 to your computer and use it in GitHub Desktop.
Save abmohan/e32001c9009c3bd35c5ff9a3a0594605 to your computer and use it in GitHub Desktop.
Flattening An Array of Arbitrarily Nested Arrays
/**
* 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;
/*
* 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