Skip to content

Instantly share code, notes, and snippets.

@area73
Last active November 12, 2018 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save area73/f378d0a7cf0b8808685df04e7255b958 to your computer and use it in GitHub Desktop.
Save area73/f378d0a7cf0b8808685df04e7255b958 to your computer and use it in GitHub Desktop.
Array flatten
// flatten Array of any deep
const flattenArray = arr => {
return arr.reduce((prev,next)=> (
Array.isArray(next)
? prev.concat(flattenArray(next))
: prev.concat(next)
),[]);
};
module.exports = flattenArray;
// Post Data
// ---------
// I believe there is now a proposal for array.protoype.flat()
// but as long it is a proposal and this is a test I try to make my own implementation using
// recursive function and a reducer
// Test file using Jest
const flattenArray = require('./flattenArray');
test('flattenArray empty', () => {
expect(flattenArray([])).toEqual([]);
});
test('flattenArray of 0 nested array', () => {
expect(flattenArray([1,2,3,4])).toEqual([1,2,3,4]);
});
test('flattenArray of 1 nested array', () => {
expect(flattenArray([1,2,[5,6],3,4])).toEqual([1,2,5,6,3,4]);
});
test('flattenArray of "n" nested arrays', () => {
expect(flattenArray([[1,2],3,[4,5,[6,[7,8]],[9,10]],11,12])).toEqual([1,2,3,4,5,6,7,8,9,10,11,12]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment