Removing zeros from an array with JavaScript's filter() method
I recently completed a coding challenge on edabit.com where one of the objectives was to remove all 0 values from an input array. Naturally I reached for the filter() method to do something like this:
const array = [1, 0, 2, 0, 3, 0, 0, 4];
function zerosGone(...nums){
return array.filter(i => i !== 0);
}
zerosGone(array)
// [1,2,3,4]
After writing that out I quickly realized I could get the same effect with the callback set up like this:
function zerosGone(...nums){
return array.filter(i => i);
}
The callback's function body simply returns values that evaluate to true and excludes those that evaluate to false -- thereby making a copy without any 0 or "falsey" values.
I guess maybe it isn't as instantly obvious, but at the same time, I am always about simplifying conditional statements whenever I can.