Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #16: map

$
0
0

Last week we took a look at the filter functionality. This week I will show you one of my favourite array methods called: “map”. It’s extremely powerful and useful in so many ways. The purpose of map is simple, it transforms an item in an array and pushes that transformation into a new array. The method then returns that newly created array with all the transformed items. A simple example will show you what it does.

var square = function (item) { return item * item; };
var squares = [1, 2, 3, 4].map(square);

In this example we just square a number in the array. The result will be a new array but with the squared items.

This example is easy to understand, but you might wonder what the practical use is for this function. Well in a lot of applications I find myself using map to select the identifier from an object and pass along a map of id’s.

var user = { id: 'UUID', version: 0, name: 'User 1' };
var users = [/* a list of users */];
var ids = users.map(function (u) {return u.id;}); 
var versions = users.map(function (u) {return u.version});
var idsAndVersions = users.map(function (u) { 
    return { 
        id: u.id, 
        version: u.version 
    };
});

These lists can be used in frameworks, api’s, ajax requests, caching, etc… everywhere you don’t need to know / send the full information of the user.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles



Latest Images