Skip to content

Instantly share code, notes, and snippets.

@richardvanbergen
Created October 15, 2018 20:15
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 richardvanbergen/611c82924fe230c4ad995453f728deb9 to your computer and use it in GitHub Desktop.
Save richardvanbergen/611c82924fe230c4ad995453f728deb9 to your computer and use it in GitHub Desktop.
export function flatten(inputArr) {
return inputArr.reduce((outputArr, input) => {
if (Array.isArray(input)) {
return outputArr.concat(flatten(input))
}
outputArr.push(input)
return outputArr
}, [])
}
import { flatten } from './flatten'
test('it can flatten two dimentional arrays', () => {
expect(flatten([[1],[2]])).toEqual([1,2])
})
test('it can flatten more than two dimentions', () => {
expect(flatten([1,2,[3,4],[[5,6],[7]],[8]])).toEqual([1,2,3,4,5,6,7,8])
})
test('it can flatten mixed value types', () => {
expect(flatten(['1',2,[3,{}],[[5,6],[[]]],[.5]])).toEqual(['1',2,3,{},5,6,.5])
})
@stefanosala
Copy link

Hi Richard,
your code looks good, thanks for your submission.

Just one question: what happens if I pass something that's not an array to the flatten function?
Could you refactor it so that it throws an error?

Thanks
Stefano

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment