Completed functionality for flatten in JS.