Click to share! ⬇️

Underscore JS Collection Functions

Underscore.js is the widely popular JavaScript library that provides a rich set of utility functions for working with the JavaScript language. Unlike PHP, JavaScript does not have thousands and thousands of built in functions to make working with data easier. Underscore fixes this by providing various functions that make it easier to deal with JavaScript Objects, Arrays, and Functions. Underscore.js is typically included in projects to offer an approach to coding in JavaScript that is both easier and more expressive than you would find with native JavaScript. You might consider Underscore as the missing functions that never were in JavaScript. In this tutorial, we’ll take a look at the <a href="https://vegibit.com/most-useful-javascript-array-functions/#Array.prototype.map">map</a> function in Underscore for working with both arrays and objects.


_.map()

The map function is used to iterate over an array and transform that array into another array. This first example snippet of the map function in action will demonstrate this for us. If you click the button to run the code, we can see that Tesla, Leaf, Volt, and Bolt are mapped from an array. When you call map and pass in electric_cars, the function gets applied to each item in that array. The map function creates a new array from the return value of the iterator function. Anytime you need to modify an array into a new one by applying a function to each element in the array, map is the function to reach for.

Array

var electric_cars = ['Tesla', 'Leaf', 'Volt', 'Bolt'], m;

m = _.map(electric_cars, function (car) {
    return car + ' is mapped from an array.';
});

Click Clear

This next example is more in the style of a declarative or functional approach. This is because we do not use an anonymous function as the iterator. In fact, less anonymous functions is probably a good thing, since anonymous functions make things very difficult to debug at a later time. Here we can see an array of fruits, along with a function of eat. To be fair, it is a variable that holds a function. What this creates is a new array of fruits as they are eaten. Some people like this approach since it is fairly easy to decipher what is happening in the code. We map the fruits through the eat function, then iterate over the new values to display to the page.

Pass Function

var fruits = ['Banana', 'Blueberry', 'Peach', 'Plum'], eat, ate;

eat = function (fruit) {
    return 'Eating a ' + fruit + '!';
};

ate = _.map(fruits, eat);

Click Clear


This final example of the map function in Underscore shows us how much some pretty cool electric bicycles cost. It begins with a data object, and within that is an array of electricbikes. Further down, there is a bikeinfo function which accepts a bike as a parameter. Inside of this function is another function of getBikeInfo and when it gets called, a string is returned based on the bike that has been passed in. Finally we see the call to the map function, and data.electricbikes is passed in as the first parameter. At this time, the anonymoust iterator function loops through and creates a new bikeinfo object while passing in the value. What results in the m variable is an array of bikeinfo objects and we then just log it out to the page for display. As we can see the map function provides the ability to take an existing array and transform it into a new array where changes have been made.

to Object Array

var data, bikeinfo, m;

data = {
    electricbikes: [
        {brand: 'Easy Motion', model: 'Big Bud Pro', cost: 3499},
        {brand: 'Haibike', model: 'XDURO FS RX 27.5', cost: 4900},
        {brand: 'IZIP', model: 'E3 Path Plus ', cost: 2299},
        {brand: 'Rad Power Bikes', model: 'RadRover ', cost: 1499}
    ]
};

bikeinfo = function (bike) {
    var getBikeInfo;
    getBikeInfo = function () {
        return 'The '
            + bike.brand
            + ' '
            + bike.model
            + ' costs '
            + bike.cost
            + '!';
    };

    return {
        getBikeInfo: getBikeInfo
    };
};

m = _.map(data.electricbikes,
    function (value, key, list) {
        return new bikeinfo(value);
    });

Click Clear


Underscore JS Map Function Summary

In this tutorial we had a good look at the map function in the popular Underscore JS library. We showed several examples of how to transform an existing dataset into a new structure rather that mutating, or modifying, the existing data. This is a common approach in functional style programming where mutation of existing state is avoided as much as possible.

Click to share! ⬇️