var nums = '1,2,3,4,5,6,7,8,9,10'.split(','); nums = $.grep(nums, function(num, index) { // num = the current value for the item in the array // index = the index of the item in the array return num > 5; // returns a boolean }); console.log(nums) // 6,7,8,9,10Or let's say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.
var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(','); arr = $.grep(arr, function(item, index) { // simply find if the current item, when passed to the isNaN, // returns true or false. If false, get rid of it! return !isNaN(item); }); console.log(arr); // 1,2,3,4,8,9
live demo
No comments:
Post a Comment