• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Programming / jQuery filter Array Method

jQuery filter Array Method

Last updated on September 29, 2013 by Sal Ferrarello

I really enjoyed Josh Clanton’s article Filtering Arrays with Array.filter on using the JavaScript filter method(). As he points out,

Because the filter method is part of the ECMAScript 5 specification, it isn’t available in older browsers like IE8.

Josh then lists a couple of options to bring this functionality into older browsers (i.e. IE < 9) using a shim or JavaScript library. He does not list a solution for the jQuery library.  After a little research I realized the jQuery method grep provides this same functionality.

While I’m not a huge fan of the method name grep for this functionality, I’m pleased it is included in jQuery (and I understand the method filter was already being used).

// subsetArray is populated by elements of
// array where the callback function returns true
var subsetArray = jQuery.grep(
  array,
  function(elementOfArray, indexInArray)
  [, invert ]
);

Example

var origArray = [
  'apple',
  'banana',
  'boat',
  'cat',
  'cow'
];

var bArrary = jQuery.grep(
  origArray,
  function(el) {
    // return true when first
    // character is 'b'
    return 'b'=== el.charAt(0)
  }
);

// bArray =
// ["banana", "boat"]<br />

photo credit: Pandiyan via photopin cc

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Programming Tagged With: JavaScript, jQuery

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in