DEV Community

Cover image for Flatten and Sort an Array of Arrays JavaScript

Flatten and Sort an Array of Arrays JavaScript

Hello Dev World Blog on January 02, 2021

Link to the video 365 days of coding day 2! How to flatten, filter, and sort and array in JavaScript. The solution for a popular intervi...
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Why would you filter out duplicates before sorting? Once sorted, duplicates will all be next to each other...

Collapse
 
hellodevworldblog profile image
Hello Dev World Blog

It isn’t really any easier if they are next to each other and if you don’t flatten first they will still be nested JS will see them as arrays not numbers to sort it will sort the parent arrays and the things within them but it won’t directly yield the results you’re looking for. You’ll still need to flatten it too lol

you could put checking for duplication as part of your loop instead of doing it after if you wanted to though!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Checking an unsorted array for duplication requires keeping track of elements you've seen before though, whereas if they're next to each other you can just walk through the array and drop elements that are the same as the previous one. For longer arrays this can be a considerable memory improvement.

Collapse
 
pavlikovinc profile image
George

Thx for explanation. It seems you forgot to change the name of the function where the recursion starts. Change it from 'flatten' to 'flattenFilterAndSort'.

Collapse
 
hellodevworldblog profile image
Hello Dev World Blog

lol thank you! I did that in the video too I have updated!