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?
Easiest way is probably
Hope this helps. Reference: https://lodash.com/docs#compact
OK, imagine we have this array below:
Let's do delete first:
and this is the result:
empty! and let's get it:
So means just the value deleted and it's undefined now, so length is the same, also it will return true...
Let's reset our array and do it with splice this time:
and this is the result this time:
As you see the array length changed and
arr[1]
is 3 now...Also this will return the deleted item in an Array which is
[3]
in this case...you can use something like this
Should display [1, 2, 3, 4, 6]
Array.remove() Method
John Resig, creator of jQuery created a very handy
Array.remove
method that I always use it in my projects.and here's some examples of how it could be used:
John's website
If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1):
var arr = ['a','b','c'];
You can use:
var indexToDelete = 1; var newArray = arr.slice(0, indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))
IndexOf
accepts also a reference type. Suppose the following scenario:Differently: