Almighty Grep



Background
I used to know the grep command in Linux as a powerful file searching utility. Its so powerful that it even helps search the content of files. I had a challenge today, I needed to populate a select control with the ordinals of certain numbers, precisely the number of floors in a building. Because I already have the number of floors in a public variable which is an array object, I do not wish to reach out to the server to fetch this value again, in order to save execution time; especially for end users with slower links.

Solution
$scope.Hostels is my public array object and it has the following structure:
{
  "ID": 1,
  "ClientiD": 2,
  "HostelName": "sample string 3",
  "HostelLocationID": 4,
  "Description": "sample string 5",
  "Gender": "sample string 6",
  "Cordinate": "sample string 7",
  "Istertiary": true,
  "IsSecondary": true,
  "IsEnterprise": true,
  "FloorsNo": 11,
  "CreatedBy": 12,
  "DateCreated": "2014-10-17T15:42:43.4807211+01:00",
  "UpdatedBy": 13,
  "DateUpdated": "2014-10-17T15:42:43.4807211+01:00"
}
 
 Notice that the FloorsNo property already holds the value that I need at runtime.
 
The Markup for my select control looks like this: 
<select class="form-control selectpicker" id="selFloor"> </select>
 
All I needed to do was populate this select control with the number of floors a building has based on selection value in another select control which holds the ID of the Hostel record I need.

Almighty Grep!
Here is where grep comes in. I found out that you could actually select a subset of an object array based on the value of any of their properties.
 
 $('#selHostelAdd').change(function () {
     var hid = $(this).val();
     var result = $.grep($scope.Hostels, function (e) { return e.ID == hid; });
     $scope.FixFloors(result[0]);
 });

 $scope.FixFloors = function (f) {
     $('#selFloor').empty();
     var newoptions;
     for (var i = 1; i <= f; i++) {
        newoptions += "<option value='" + i.toString() + "'>" + $scope.GetOrdinal(i) + "</option>";
      }
     $('#selFloor').append(newoptions);
}

From my code above, you will notice that after a selection is made, I simply selected the matching array element using $.grep as follows: 
 
var result = $.grep($scope.Hostels, function (e) { return e.ID == hid; });
 
$scope.Hostels is the source array, and result is the resultant array containing the matching element(s).
 
Eureka! 

Comments

Popular posts from this blog

Determine Appropriate Font-Size for Text iTextSharp

Consume ASP.NET Web API Using PHP and JQuery

T-SQL: Prudent use of Select ... As