Last Updated: June 07, 2016
·
339
· 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'

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside