Remove Null Elements From Array With Javascript (like Ruby Array#compact)

Remove Null Elements From Array With Javascript (like Ruby Array#compact)

For those coming from Ruby, Javascript has no builtin method like Ruby’s Array#compact. This method removes nil items from a an array. For example, if you have an array with 5 items, where 2 are nil, compact would shrink the array down to 3 items like this:

arr = [nil, "say", "kenglish", "co", nil]
arr.compact
# returns new array with ["say", "kenglish", "co"

How to do an Array compact with pure JS

With pure javascript, the best option is to use Array.prototype.filter(), for example:

list = [null, "say", "kenglish", "co", null]
list.filter(function(obj) { return obj });
// Or with es6
list.filter((obj) => obj );
// return new array [ 'say', 'kenglish', 'co' ]

How to do an Array compact with RamdaJS

Another option is the use the functional library Ramda, while the syntax may be a bit different from the Ruby and Pure JS version, I find it to be more declarive:

list = [null, "say", "kenglish", "co", null]
R.reject(R.isNil, list)
// return new array [ 'say', 'kenglish', 'co' ]

It is important to note that all 3 of the examples will return a new verion Array of the array leaving the orignal version intact