What is the difference between using the delete
operator on the array element as opposed to using the Array.splice
method?
For example:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
Why even have the splice method if I can delete array elements like I can with objects?
Delete element from last
Delete element from first
Delete from middle
Delete one element from last
Delete by using array index number
They're different things that have different purposes.
splice
is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.)splice
will change thelength
of the array (assuming it's not a no-op call:theArray.splice(x, 0)
).delete
is not array-specific; it's designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren't really arrays at all*, they're objects with special handling for certain properties, such as those whose names are "array indexes" (which are defined as string names "...whose numeric valuei
is in the range+0 ≤ i < 2^32-1
") andlength
. When you usedelete
to remove an array entry, all it does is remove the entry; it doesn't move other entries following it up to fill the gap, and so the array becomes "sparse" (has some entries missing entirely). It has no effect onlength
.A couple of the current answers to this question incorrectly state that using
delete
"sets the entry toundefined
". That's not correct. It removes the entry (property) entirely, leaving a gap.Let's use some code to illustrate the differences:
* (that's a post on my anemic little blog)
Currently there are two ways to do this
using splice()
arrayObject.splice(index, 1);
using delete
delete arrayObject[index];
But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.
delete Vs splice
when you delete an item from an array
when you splice
in case of delete the element is deleted but the index remains empty
while in case of splice element is deleted and the index of rest elements is reduced accordingly
For those who wants to use Lodash can use:
myArray = _.without(myArray, itemToRemove)
Or as I use in Angular2