Skip to content

Instantly share code, notes, and snippets.

@Kieranties
Created July 6, 2011 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kieranties/1067038 to your computer and use it in GitHub Desktop.
Save Kieranties/1067038 to your computer and use it in GitHub Desktop.
Filtering an array using Javascript 1.6 or jQuery
var arr = [0, 1, 2, 3, null, undefined, '', "test"];
/* Remove 'falsy' values */
//using the filter method available in Javascript 1.6
var output = arr.filter(function(x){return !!x});
console.log(output)// [1, 2, 3, "test"]
//using jQuery grep function
var jqOutput = $.grep(arr, function(x){return !!x});
console.log(jqOutput )// [1, 2, 3, "test"]
/* Get numbers */
//filter
var numOutput = arr.filter(function(x){return typeof x === "number"});
console.log(numOutput )// [0, 1, 2, 3]
//jQuery grep
var jqNumOutput = $.grep(arr, function(x){return typeof x === "number"});
console.log(jqNumOutput )// [0, 1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment