Skip to content

Instantly share code, notes, and snippets.

@jasonnathan
Created December 6, 2016 10:54
Show Gist options
  • Save jasonnathan/fecfed50805a9f28bc04a797498a219b to your computer and use it in GitHub Desktop.
Save jasonnathan/fecfed50805a9f28bc04a797498a219b to your computer and use it in GitHub Desktop.
A simple way to flatten an array
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;
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