Mapping and Pruning Arrays
I find myself constantly mapping and then reducing empty entries in an array. It happens often enough that I decided to create a helper function that uses maps and then prunes the empty entries. Does anyone else do this? Do you have a more concise/less error prone ways of doing this? Maybe chaining _.clean()
from lodash?
// the function I keep coming back to
function mapPrune (array, callback) {
return array
.map(callback)
.filter( function (el) {
return el;
});
}
// example use
var array = ['', 'no', '', '', '', 'empty', 'values', '', '', '' ];
array = mapPrune( array, function (el) {
// Test the value
if (el) return el.toUpperCase();
});
console.log(array.join(' '));
// logs 'NO EMPTY VALUES'
Written by coffeeCola
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#