Removing object property and array element in JavaScirpt is quite a different world. It is one of defining features that differentiate prototypal from classical OO languages.
Objects vs Arrays
First thing first, what are objects and arrays in JavaScirpt?
An array, declared using ‘[ ]’, is made up of a list of indexed elements. It works like a collection or list depends on which language you compare it to, and therefore comes with push, pop and other methods as expected.
An object, declared using ‘{ }’, implemented like associative arrays, or set in mathematical terms, has one or more key-value pairs as its properties. And because it is in the prototypal world, meaning objects are mutable, you can modify its properties on the fly as you wish.
Deleting Properties from an Object
Assuming an objet like this:
The question of 'how can I remove properties from an object' has been asked over and over again, with surprisingly high ratings.
Apparently, the best way is to use delete operator.
This way, the property key value pair will be removed from the object, for good.
Modifying an Array
Given the following array:
If you try to employ the delete method like it is in object,
Your array will end up with a big black hole in the middle.
Unless that’s what you want, the best way to remove some elements from an array is either to slice or splice.
When slicing an array, you are creating a new array from a portion of the existing array. Meanwhile, the original array stays untouched.
While splicing an array, the content of the exiting array is changed, as well as spitting out the elements as a new array.
Additionally, as a handy way to clean up the empty elements in an array, you can also include this in your code.