Remember to filter your arrays before doing array-wise operation. Filtering falsy values must be the first operation even if you do not have specific filtering requirements.
Consider this array -
|
|
If you are in control of the data source, you can very well expect to filter only when necessary. But any kind of array operations, or data from external systems can cause all kinds of unexpected results.
We have seen how unexpected values impact array sort before. As you can imagine filtering goes beyond a simple array sort.
Thanks to the loose-typing, Javascript can come back with surprises when least expected. The only defensive programming technique in those cases is to check for data before runtime starts throwing a tantrum.
Filtering arrays is one of those techniques.
If you are well aware of the validations that go in the array element, it may be a good idea to apply some of those simple validations to check data sanctity.
Else, consider a simple true/false check, and apply filter on the array. We have seen this before.
|
|
A simpler way to do that can be -
|
|
I personally prefer the more readable format using anon function - it is more explicit. Both ways lead to similar results.