maxhallinan
maxhallinan

Reputation: 1329

jQuery.map() and undefined

In playing with jQuery's utility method, jQuery.map(), I noticed that an undefined return value is omitted from the returned array. What is the reason for this?

var letters = ['a', undefined, 'c', undefined, 'e'];
console.log(letters); //["a", undefined, "c", undefined, "e"] 
console.log(letters.length); //5 

var lettersMapped = $.map(letters, function(item, index){
    var item = item;
    return item;
});

console.log(lettersMapped); //["a", "c", "e"]
console.log(lettersMapped.length); //3

Upvotes: 4

Views: 1726

Answers (1)

Hamish
Hamish

Reputation: 23316

Per the documentation for jQuery.map:

The function can return:

  • the translated value, which will be mapped to the resulting array
  • null or undefined, to remove the item
  • an array of values, which will be flattened into the full array

In other words, this is the expected behaviour of jQuery.map.

Upvotes: 2

Related Questions