Tips – Javascript Arrays – Refactoring to Filter and Map.


When learning a new language or implementing something new, I tend to “get it working” first which usually doesn’t include elegant code, unless I have written Libraries or extension methods previously to fit the solution. One of these was using Arrays in Javascript. Basically i needed to find the Active User, which was for a client side collection of users for an Admin. So my “get it working” code is the legal (but definitely not regal code), which is a simple function that returns a array of usernames, of people who are Active (i.e. login and use the site):

 

JSFiddle is here.

function getActiveUsers(people) {

    var activeUsers = [];
    var ii = 0;
    for (var i = 0; i < people.length; i++) {

        if (people[i].isActive == true) {
            activeUsers[ii] = people[i].userName;
            ii++;
        }
    }    return activeUsers;
}

Anyway, as I’m learning Javascript presently, I have been reading about prototyping in Javascript and especially about some existing functionality that resides with the Array global object (under Array.prototype). Specially I’m talking about:

Array.prototype.filter()

Array.prototype.map()

 

NB: As those Links note, the Array.prototype property was only introduced within the ECMAScript spec 5.1 (ECMA-262) Edition. This will mean adding some Polyfil code (also provided in the links above) if you wish to use this within old browsers.

Anyway, using these two new methods I was able to go back over my previously “get it working” code above, refactor it and use some of the nicely provided filter and map methods:

JSFiddle is here.

function getUserName(user) {
  return user.userName;
}

function isActive(user) {
  return user.isActive;
}

function notActive(user) {
  return !isActive(user);
}

function getActiveUsers(user){
  return user.filter(isActive).map(getUserName);
}

function getNonActiveUsers(user) {
    return user.filter(notActive).map(getUserName);
}

So now I call into this new getActiveUsers which passes the callback function isActive, which basically only gives me back items from the array where the property user.IsActive is true. The chained map function passes the callback function of getUserName to retrieve the userName only. I have also created the opposite functions as well – i.e. Non-Active users. Both JSFiddles show the code in action, but i goes to show that a little reading, research and thought can help improve code readability and re-usability a great deal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s