THE MEMORY OF THE CITY
log in
Samantics
js Arrays and delete
2019-11-27 19:20:01

js Arrays and delete

Consider:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals);
delete animals[2];
console.log(animals);

console.log(animals.filter((x) => { return x !== undefined; }));


This produces the output:

> Array ["ant", "bison", "camel", "duck", "elephant"]
> Array ["ant", "bison", undefined, "duck", "elephant"]
> Array ["ant", "bison", "duck", "elephant"]


Sometimes you just need to iterate over a non-iterable collection and delete things as you go. Now you can clean up after and not feel bad about it.

This question has been asked quite a lot by newbies, and they are invariably told to just use Array.prototype.splice(), but that has the annoying habit of immediately re-indexing the array.

I should probably mention that using delete on Array elements is slightly undefined behaviour; at least one checker (JSlint) apparently dislikes it. But the MDN page for Array is almost weirdly glib about casually discussing implementation details, so we'll just say YMMV.
Samantics 8456.268 tgc / 2019.905 ce