Blog

JavaScript SQL-like Filtering

Here are some handy JavaScript functions to filter Arrays in SQL-like fashion

            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;
            };