Skip to content

Instantly share code, notes, and snippets.

@alejandroiglesias
Last active September 6, 2016 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alejandroiglesias/24ce42d4c55ded3a517a2f8dd4c4617b to your computer and use it in GitHub Desktop.
Save alejandroiglesias/24ce42d4c55ded3a517a2f8dd4c4617b to your computer and use it in GitHub Desktop.
Recursively flattens arbitrarily nested arrays.
/**
* Recursively flattens arbitrarily nested arrays.
*
* @param {Array} array The array to flatten.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function flattenArray(array, result = []) {
if (!Array.isArray(array)) throw new TypeError('Called on non-array.');
array.forEach(item => {
if (Array.isArray(item)) {
// Recursively flatten array.
flattenArray(item, result);
return;
}
result.push(item);
});
return result;
}
export default flattenArray;
import flattenArray from '../../src/flatten-array';
describe('flattenArray', () => {
it('it should flatten simple nesting', () => {
const nestedArray = [1, 2, 3, [4]];
const flatArray = flattenArray(nestedArray);
expect(flatArray).to.be.an('array');
expect(flatArray).to.deep.equal([1, 2, 3, 4]);
});
it('it should flatten complex nesting', () => {
const nestedArray = [[1,2,[3]],4];
const flatArray = flattenArray(nestedArray);
expect(flatArray).to.be.an('array');
expect(flatArray).to.deep.equal([1, 2, 3, 4]);
});
it('it should throw if passing a non array', () => {
expect(flattenArray).to.throw(TypeError);
expect(flattenArray.bind(null, 123)).to.throw(TypeError);
expect(flattenArray.bind(null, [1, 2, 3])).not.to.throw(TypeError);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment