In this post we will see how we can filter array of element without empty element which can be null or ''
Using javascript
Javascript .filter() method creates a new array with all elements that pass the test implemented by the provided function.
1
arr = ['apple', 'banana', '', 'mango', null, undefined]
From the given array of elements we can easily get non empty elements by using .filter() method:
1
2
arr.filter(fruit => fruit)
> (3) ['apple', 'banana', 'mango']
This works because only non-empty elements will return true from the callback function
Using Ruby
In Ruby .reject() method returns a new array containing the items in self for which the given block is not true. The ordering of non-rejected elements is maintained.
1
arr = ['apple', 'banana', '', 'mango', nil]
NOTE:
blank?method will return true for both''andnilvalues
empty?method will return true for''but throwundefined method empty? for nil classfornilvalues
nil?method will return true forniland false for''values
1
2
3
4
5
6
7
8
9
10
11
# using blank?
arr.reject &:blank?
=> ["apple", "banana", "mango"]
# using empty?
arr.reject &:empty?
=> undefined method 'empty?' for nil:NilClass
# using nil?
arr.reject &:nil?
=> ["apple", "banana", "", "mango"]