The Set object in JavaScript preserves insertion order. So if you create a Set from an array, it will preserve the order when you spread it back out (but without duplicates).
I was under the impression that, because sets (the data structure) do not have an order, you wouldn't be able to guarantee order when you spread it, but that to totally wrong.
It will have issues with anything non-serializable, explicitly set undefineds will disappear on objects (if that matters), and undefined inside arrays will turn into null. And maybe some other edge cases I'm forgetting.
It will implode on undefined, circular references, and most appallingly, objects with different key orders. Not really obscure edge cases. People really need to stop using the JSON trick.
You don't need to create an arrow function each time you want to call only one function. This works:
[ ... new Set(arr.map(JSON.stringify))].map(JSON.parse)
You would need though if the function depended on the context (the JSON object in this case isn't needed for the function itself), or you could .bind it too
It depends. If I've got a list of 10 items, this is totally fine. Sure it's I'm using more space than I need, but it's pretty negligible and as long as it's not in the global context, the memory is going to be released soon enough anyway. If I've got a list of two million items, of course this is stupid.
One liners often trade performance for terseness, which is what this does. The question asked wasn't "Write the most performant code you can", it was "what is your favorite one liner" and that's what this is.
If you're writing JS code where literally every single byte counts, more power to you, but most people aren't. This is perfectly acceptable for small arrays.
Ideally sets would have some useful methods so you could work with them directly more often. See proposals: 123. But for now it's acceptable for my personal use cases.
If the Set uses hashing, then it's O(n). It will iterate through the list and add each item to the set. Adding an item requires checking for uniqueness which can be O(1) assuming the underlying data structure is some kind of hash table. If it's not, then it would have to iterate through the current items. This would be O(n2).
339
u/Drugba Mar 19 '19
Saw this one on here just a few weeks ago.
Basically a super short way to remove any duplicates from an array of primitives.