Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array.prototype.filter remove empty elements regardless of the callback?

I have an array with some empty elements in it and I am calling .filter on that array with a callback that always returns true.

[1, 2, , 5].filter(() => true);

The result of the above code is [1, 2, 5] - the empty element is no longer there. This isn't what I'd expect, because the callback returns true.

For comparison, Array.prototype.map does execute the callback for empty items:

[1, 2, , 5].map(x => x); // returns [1, 2, , 5]
like image 320
James Monger Avatar asked Dec 07 '25 06:12

James Monger


1 Answers

In map, the callback is not called for each element (as you can see by logging the value inside the callback to map), but keys are preserved, leaving the empty slots in the result. Filter does not preserve keys (as filtering often shifts keys around), so those are lost. Neither operation actually runs the callback on empty slots, though.

like image 187
IceMetalPunk Avatar answered Dec 09 '25 19:12

IceMetalPunk