Last Updated: June 07, 2016
·
116
· coffeeCola

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'