Skip to content

Instantly share code, notes, and snippets.

@ellismarkf
Last active August 15, 2016 15:47
Show Gist options
  • Save ellismarkf/47eef3d18374e7c8e8beff8274547c09 to your computer and use it in GitHub Desktop.
Save ellismarkf/47eef3d18374e7c8e8beff8274547c09 to your computer and use it in GitHub Desktop.
javascript array utility that flattens an arbitrarily nested array of arrays of integers

flatten

Just a small function that does as the description explains: flattens an arbitrarily nested array of arrays of integers. Uses a recursive strategy to handle nesting, and written in a functional style.

This implementation assumes that arrays only contain integers, not any other primitives. The logic that decides whether to recursively call the function again is predicated on the presence of a length property, which Integers in Javascript do not have. Passing an array containing other primitives to the flatten function will result in a runtime error.

usage

git clone https://github.com/ellismarkf/flatten.git
cd flatten
npm install

To use the flatten function, either require('/path/to/flatten.js') or import flatten from '/path/to/flatten'.

var flatten = require('./flatten.js');
var flattenedArray = flatten(someNestedArray);

testing

The flatten function is unit tested using the mocha framework, with the chai assertion library. You'll need mocha installed globally to run the tests. Run the unit tests with either mocha or npm test at the top level of the project directory.

npm i -g mocha
npm test
function flatten(array) {
return array.reduce( function(result, element) {
if (element.length) {
return result.concat(flatten(element));
} else {
return result.concat(element);
}
}, []);
}
module.exports = flatten;
var expect = require('chai').expect;
var flatten = require('./flatten.js');
describe('flatten', function() {
it('should return an array with length property equal to the number of integers in nested array', function() {
var nestedArray = [[1,2,[3]],4];
var flattenedArray = flatten(nestedArray);
expect(flattenedArray.length).to.equal(4);
});
it('should return an array containing all elements of nested array', function() {
var nestedArray = [[1,2,[3]],4];
var expectedResult = [1, 2, 3, 4];
var flattenedArray = flatten(nestedArray);
expect(flattenedArray).to.eql(expectedResult);
});
it('should flatten an array of arbitrarily nested arrays of integers into a flat array of integers', function() {
var nestedArray = [[[1, 2], [3, [4, 5, 6, [7]]]], 8, [9, [10, [11]]]];
var expectedResult = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var flattenedArray = flatten(nestedArray);
expect(flattenedArray.length).to.equal(11);
expect(flattenedArray).to.eql(expectedResult);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment