Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter items in JavaScript Array using jQuery

I have a JavaScript array as below which I need to filter to get the correct child values from the test data below.

var arrChildOptions2 = [
        {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
        {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'},
        {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'}
    ];

The values are used to populate a dropdown based on the change event of a parent dropdown as below.

$(function() {
    $('#ddl1').change(function() {
        $('#ddl2 option:gt(0)').remove();
        $('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]);
    });
});

where additems is a function that loops through the array. Problem is I can't get it to filter by parent, I've tried using contains and the above arrChildOptions2[Parent=opt2] but I can't get it to filter, I'd prefer to find a neat solution rather than use a for loop? Any ideas, cheers

like image 254
Israfel Avatar asked Jan 18 '10 09:01

Israfel


2 Answers

You might have more luck using the jQuery.grep() function rather than messing around with loops.

This function "Finds the elements of an array which satisfy a filter function. The original array is not affected".

like image 96
Phil.Wheeler Avatar answered Oct 20 '22 18:10

Phil.Wheeler


array.filter() exists in vanilla JavaScript:

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

That documentation page includes a polyfill for older browsers:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}
like image 27
Blazemonger Avatar answered Oct 20 '22 19:10

Blazemonger