Skip to content

Instantly share code, notes, and snippets.

@timurridjanovic
Last active August 4, 2016 22:17
Show Gist options
  • Save timurridjanovic/83218342c5e4a4536693d9c01f268a9c to your computer and use it in GitHub Desktop.
Save timurridjanovic/83218342c5e4a4536693d9c01f268a9c to your computer and use it in GitHub Desktop.
Flatten an array
function flatten(arr) {
if (!Array.isArray(arr)) throw new Error('flatten takes an array as a parameter');
return arr.reduce(function(newArr, el) {
if (Array.isArray(el)) return flatten(newArr.concat(el));
return newArr.concat(el);
}, []);
}
//uses jasmine as a testing framework
describe('Flattening an array', function() {
it('should flatten nested array of integers to an array of integers', function() {
var arr = [1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[10, 11, [12, 13]]]]], 14];
expect(flatten(arr)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]);
});
it('should flatten nested array of generic types to an array of generic types', function() {
var arr = [1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[{name: 'hello'}, 'foo', [12, 13]]]]], 14];
expect(flatten(arr)).toEqual([1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[{name: 'hello'}, 'foo', [12, 13]]]]], 14]);
});
it('should return empty array', function() {
expect(flatten([])).toEqual([]);
});
it('should throw an error', function() {
expect(function() { flatten({}); }).toThrow(new Error('flatten takes an array as a parameter'));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment