Skip an element with jQuery's $.map

Dany Khalife picture Dany Khalife · Jun 16, 2013 · Viewed 10.4k times · Source

I have a jQuery object obj that encapsulates a set of input elements.

I am using this code in order to make an array out of each element's value :

$.map(obj, function(elem, i){
    return $(elem).val();
});

The problem is that sometimes some of the input fields contain invalid values and i would like to skip them in the process of creating the array. Doing a simple return false doesn't seem to skip the element but instead inserts a false in the array.

I would like to know if there is a way to actually do that without using .each explicitly.

Answer

mekwall picture mekwall · Jun 16, 2013

Since it's an jQuery collection, you can execute .map directly and then use .get so that it becomes an array.

var values = obj.map(function(){
    return this.value ? this.value : null;
}).get();

Note: The above check will return any value that isn't falsey.

See test case on jsFiddle.