Created
December 6, 2016 10:54
-
-
Save jasonnathan/fecfed50805a9f28bc04a797498a219b to your computer and use it in GitHub Desktop.
A simple way to flatten an 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
const flatten = (arr) => arr.reduce( | |
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] | |
); | |
// es5 version | |
var flattenES5 = function flatten(arr) { | |
return arr.reduce(function (a, b) { | |
return a.concat(Array.isArray(b) ? flatten(b) : b); | |
}, []); | |
}; | |
export default flatten; |
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
import flatten from './flatten.js' | |
const chai = require('chai'); | |
const {expect} = chai; | |
describe("flatten()", function(){ | |
it("should throw an error if the given a non array as an argument", function(){ | |
expect(() => flatten("")) | |
.to.throw(Error, "flatten needs an Array as an argument. `string` given instead") | |
}); | |
it("should flatten an array of nested arrays", function(){ | |
expect(flatten([[1,2,[3]],4])).to.eql([1,2,3,4]); | |
expect(flatten([1, ["string"], [], [{obj:[]}]])).to.eql([1,"string",{obj:[]}]); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment