filter empty element from an array
I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.
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.
arr = ['apple', 'banana', '', 'mango', null, undefined]
From the given array of elements we can easily get non empty elements by using .filter() method:
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.
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
# 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"]

