Array sorting is one of those things you don’t spend too long thinking about, until it stops working for you. Recently I was working with array of ...
For further actions, you may consider blocking this person and/or reporting abuse
Hi Phil, this is a great writeup! Do you mind if I link to this at the bottom of my recent article on JavaScript sorting? I'd love to direct people to the inconsistencies and gotchas with nulls and undefineds. :)
I would love it if you wanted to link to it! Thanks!
Thanks Phil! Link has been added! :)
(dev.to/isalevine/a-quick-review-of...)
I think the biggest disadvantage of
sort()
is that it sorts in place.You need to do some relatively ugly hacks like spreading:
in order to use the power of FP.
it returns an array of
undefined
s :/That's because the
console.log
returnsundefined
, and it's being used in the call to.map()
.exactly, my point is we should not use
map
here at all.Yeah, it is a shame that it acts in place as we move to code that attempts to reduce the number of side effects. At least we can work around it, the problem is just remembering to.
Hi Phil,
would not have been the case to use lodash for undefined and null ?
This would have worked as well, therefore you might not need lodash.
Hi Stefano, not sure what you mean there. Could you explain more?
lodash.com/docs/4.17.15#compact
Wow. Using lodash for that. Wow. :)
Oh, sure, I could have used that. I’d probably prefer to just use an array
filter
though, as I do later in the post, as it will only filter the things I want and don’t incur the overhead of requiring a library like (or even just a function from) lodash.Hmm, i always filter the falsy values by doing
arr.filter(x => x)
(i probably would do that if i wanted <1 numbers in there though ;)I like
Nice one, didnt know that one :)
They are both cool filter expressions! 😎
But... they both lose
0
or''
which you might not want. That's why I like theundefined
check.Very informative, thank you! 😊👌💪
Glad you enjoyed it, thanks!