Last active
July 26, 2016 22:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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