Skip to content

Instantly share code, notes, and snippets.

@matiasfha
Created October 7, 2019 17:54
Show Gist options
  • Save matiasfha/24abcb0ad815dbcca5d256600f2e3a7e to your computer and use it in GitHub Desktop.
Save matiasfha/24abcb0ad815dbcca5d256600f2e3a7e to your computer and use it in GitHub Desktop.
Array flatten for es6
/* This function use array.reduce
* https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/reduce
* to recursively flatten a multidemensional array.
* The array can be arbitrarly deep
*/
const flatten = list => list.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);
// Testing with chai and mocha
describe('Array flatten', function() {
it('Should return a flat version of a bi-dimensional array', function() {
const array = [[1,2],[3,4]]
const flat = flatten(array)
const truth = flat.flat(Infinity)
expect(flat).to.have.length(truth.length)
expect(flat).to.have.deep.members(truth)
})
it('Should get a flat version of complext array', function() {
/** Boilerplate to generate random custom nested array */
const genObject = () => ({
id: Math.ceil(Math.random()*100),
value: Math.random()
})
const genTotal = () => {
return Math.ceil(Math.random()*100)
}
const genNestedBoard = ({ width, height}) =>
Array.from({ length: height}, () => Array.from({ length: width }, () => genObject() )
);
const nested = genNestedBoard({ width: genTotal(), height: genTotal() })
const flat = flatten(nested)
const truth = flat.flat(Infinity)
expect(flat).to.have.length(truth.length)
expect(flat).to.have.deep.members(truth)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment