jQuery Filter JSON Data

by santhosh lanka

HTML

<div id="DrpDwn">
        Year:<select id="DropDown_Year"><option>Year</option></select>
        Make:<select id="DropDown_Make"><option>None</option></select>       
</div>
<br />
Filtered product information
    <table id="details"  border="1" cellpadding="2" cellspacing="2">
    <thead>
        <tr>
            <th >Year</th>
            <th>Make</th>
            <th>Model</th>
        </tr>
    </thead> 
    <tbody></tbody>   
</table>

CSS

th,td
{
   width:100px;
}

JavaScript

var ProductInfo = [{
    Year: "2011",
    Make: "Product 1",
    Model: "101"
},
{
    Year: "2011",
    Make: "Product 2",
    Model: "x101"
},
{
    Year: "2010",
    Make: "Product 3",
    Model: "234"
},
{
    Year: "2011",
    Make: "Product 4",
    Model: "100"
},
{
    Year: "2012",
    Make: "Product 5",
    Model: "500"
},
{
    Year: "2011",
    Make: "Product 6",
    Model: "100"
},
{
    Year: "2013",
    Make: "Product 7",
    Model: "100"
},
{
    Year: "2013",
    Make: "Product 8",
    Model: "455"
}];
var yearsArray = ["2013", "2012"];
var makesArray = [];

// adding unique years to yearsArray
$.each(ProductInfo, function (index) {
    var year = ProductInfo[index].Year;
    if ($.inArray(year, yearsArray) == -1) {
        yearsArray.push(year);
    }
});
//sorting the year 
yearsArray.sort();
var $yearDropDown = $("#DropDown_Year");
var $makeDropDown = $("#DropDown_Make");
var $container = $("#details").find("tbody");
// append the years to select
$.each(yearsArray, function (i) {
    $yearDropDown.append('<option value="' + yearsArray[i] + '">' + yearsArray[i] + '</option>');
});

$yearDropDown.change(function () {
    var selectedyear = this.value;
    //filter based on  selected year.
    makesArray = jQuery.grep(ProductInfo, function (product, i) {
        return product.Year == selectedyear;
    });
    $makeDropDown.empty();
    $makeDropDown.append('<option>None</option>');
    for (var i = 0; i < makesArray.length; i++) {
        $makeDropDown.append('<option value="' + makesArray[i].Make + '">' + makesArray[i].Make + '</option>');
    }
    updateTable(makesArray);
});

$makeDropDown.change(function () {
    var selectedMake = this.value;
    //filter select based on selected Make
    selectedArray = jQuery.grep(ProductInfo, function (product, i) {
        return product.Make == selectedMake;
    });
    updateTable(selectedArray);

});
//To update the table element with selected items
updateTable = function (collection) {
   ...