Last active
February 6, 2018 06:49
-
-
Save krishnasaga/3d7cd97712e3438581807c584b7b2b6e to your computer and use it in GitHub Desktop.
Flatten Array
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
var flatten = function(array) { | |
return array.reduce(function(a,b) { | |
return a.concat(Array.isArray(b) | |
? flatten(b) | |
: [b] ); | |
},[]); | |
}; |
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
var flatten = function(array) { | |
var flatArray = []; | |
array.forEach(function(element) { | |
Array.isArray(element) | |
? flatArray = flatArray.concat(flatten(element)) | |
: flatArray.push(element); | |
}); | |
return flatArray; | |
}; |
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 flatten the array',function(){ | |
expect(flatten([1,2,3,4])).to.be.an.array().and.to.equal([1,2,3,4]); | |
expect(flatten([[1,2],[3,4]])).to.be.an.array().and.to.equal([1,2,3,4]); | |
expect(flatten([1,[2,3],4])).to.be.an.array().and.to.equal([1,2,3,4]); | |
expect(flatten([1,[2,[3,4],5,6,7]])).to.be.an.array().and.to.equal([1,2,3,4,5,6,7]); | |
}); | |
}); |
Author
krishnasaga
commented
Dec 5, 2016
const flatten = arr => arr.reduce((a,e) => a.concat(Array.isArray(e) ? flatten(e) : e), [])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment