Last active
November 12, 2018 03:01
-
-
Save area73/f378d0a7cf0b8808685df04e7255b958 to your computer and use it in GitHub Desktop.
Array flatten
This file contains hidden or 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
// 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 |
This file contains hidden or 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
// 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