Pages

Friday 26 April 2013

JavaScript Array Delete Elements

Q. 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);
 
 

Ans.

Delete won't remove the element from the array it will only set the element as undefined.
So,

> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray
[undefined, "b", "c", "d"]
> myArray.splice(0, 2)
[undefined, "b"]
> myArray
["c", "d"]
 
 

Array.remove() Method

John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
and here's some examples of how it could be used:
// Remove the second item from the array
array
.remove(1);
// Remove the second-to-last item from the array
array
.remove(-2);
// Remove the second and third items from the array
array
.remove(1,2);
// Remove the last and second-to-last items from the array
array
.remove(-2,-1);

No comments:

Post a Comment