BlogJavaScript. Two Dimensional ArraysTwo 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:
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:
Loading blog_post_recommendations...
|