Created
July 6, 2011 11:34
-
-
Save Kieranties/1067038 to your computer and use it in GitHub Desktop.
Filtering an array using Javascript 1.6 or jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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