Skip to content

Instantly share code, notes, and snippets.

@juanmirod
Last active July 26, 2016 22:12
Show Gist options
  • Save juanmirod/e446a70d0ce9d4653ff985955afa4857 to your computer and use it in GitHub Desktop.
Save juanmirod/e446a70d0ce9d4653ff985955afa4857 to your computer and use it in GitHub Desktop.
Function that flattens a nested array. You can see the result of the tests in this jsbin: http://jsbin.com/suvocovuzi/edit?html,js,output
describe('Flatten', function() {
it("Should put scalar values inside an array", function() {
expect(flatten(1)).toEqual([1]);
});
it('Should leave arrays as they are', function() {
expect(flatten([1, 2, 3, 4])).toEqual([1, 2, 3, 4]);
});
it('Should flatten nested arrays', function() {
var arrayToFlatten = [[1, 2, [3]], 4];
expect(flatten(arrayToFlatten)).toEqual([1, 2, 3, 4]);
});
});
function flatten(toFlatten) {
if (!Array.isArray(toFlatten)) {
return [toFlatten];
}
return toFlatten.reduce(function(flat, nextElem) {
return flat.concat(flatten(nextElem));
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment