Blog

JavaScript. Two Dimensional Arrays

Two dimensional arrays are everywhere. For instance, all data coming from a database table would probably find its way to you as a two dimensional array. Here is an example of one:

[ 
    { "id":1, "first_name":"Tinna", "last_name":"Donne", }
    { "id":2, "first_name":"Joanne", "last_name":"Smith", }
]

 

Working with 2 dimensional arrays in JavaScript is not the nicest of experience. The standard Array functions do not provide anything out of the box to help with.

Here are a few functions, attached to the Array prototype, which can make your life easier, when sorting through two dimensional arrays.

 

Array.prototype.selectOne = function (where) {
    var filtered = this.selectWhere(where);
    if (filtered.length > 0) {
         return filtered[0];
      }
     return null;
};
Array.prototype.selectWhere = function (where) {
    var columnName = where[0];
    var comparator = where[1];
    var compareValue = where[2];
    var filtered = [];

     for (var i = 0; i < this.length; i++) {
        var row = this[i];
        if (row[columnName] == compareValue) { // Leave as is, do not use "==="
             filtered.push(row);
         }
    }
    return filtered;
};

Here is an example how to use:

// Get the person with ID=2
var person = people.selectOne(['id','=','2']);
// Get the person with last name Smith
var person = people.selectOne(['last_name','=','Smith']);
// Get all the people whose first name is Joanne
var joannes = people.selectWhere(['last_name','=','Smith']);