This site has a similar question: Possible to push empty slot to an array? I want to know if it’s possible for the Array.prototype.map
callback to return an empty slot.
I tried this but it returns undefined
instead:
console.log([1, 2, 3].map(() => {}));
I want to return empty slots so that I can simply call flat()
on the return value to remove them. flat()
does not remove undefined
or null
values.
I’m aware of the .filter(Boolean)
trick, but I don’t like that solution because 0
is falsey, and I’ve never intended to remove that as a side effect of removing null
/undefined
elements: in my experience, .filter(Boolean)
is a ticking time bomb in one’s code.
4
Answers
Use an empty array instead:
No, this is not possible. A (callback) function always returns a value (or throws an exception), whereas an empty slot is "created" by the absence of a value. An empty slot is a property that does not exist despite being between
0
and the array’s.length
. Themap()
function always creates properties for the values returned from the calls to the callback function.No it is not possible to return an empty slot from
Array.prototype.map
, because a reference to the array being built is not passed tomap
‘s argument function, and empty slots are created by increasing the length of an array by setting it’slength
property, or using thedelete
operator on an element within the array.Out of interest, here’s an simple example of creating a sparse array by setting its
length
:[Note: in the above code, the snippet
console.log
function does not appear to conform to the standard to log remaining arguments which follow formatting string arguments and the values which the format string consumes.]A very ordinary alternative would be to iterate over an input array and push elements to be kept to an output array, or not push them if they are not required in flat array output.
This feels like what you are asking. If not, what am I missing?
Edit
I think the hangup is that you’re asking for empty slots, and then suggesting using
array.prototype.flat
to clean up those empty slots. It feels like most know thatflat
concatenates nested arrays, but it also cleans up sparse arrays.There seem to be only a few ways to create sparse arrays, and
array.prototype.map
is not one of them. Sparse Array