DEV Community

loading...

Discussion on: Flatten and Sort an Array of Arrays JavaScript

Collapse
darkwiiplayer profile image
DarkWiiPlayer

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 Author

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
DarkWiiPlayer

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.