RSS

Remove Array element by Index / Value

04 Jul

Remove Array element by Index:

First we will see an example were we will remove array element by its index. For this we can define a generic function removeByIndex().

function removeByIndex(arr, index) {
    arr.splice(index, 1);
}

In above code we used javascript splice() method to remove element at an index. splice() method takes two argument. First is the index at which you want to remove element and second is number of elements to be removed. In our case it is 1.

To test the above code lets define a simple array and remove one of the element.

Example:

test = new Array();
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
removeByIndex(test, 2);
alert("Array after removing elements: "+test);

Also you may want to define removeByIndex method with an array so that you call it directly. For example, in following example, we have define an array test and its method removeByIndex().

Example:

test = new Array();
//define removeByIndex method as part of the array
Array.prototype.removeByIndex = function(index) {
    this.splice(index, 1);
}
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
test.removeByIndex(2);
alert("Array after removing elements: "+test);

Remove Array element by Value:

You may want to remove array element by its value and not index. This can be easily done by iterating through it and comparing the values, if a match is found we can remove that element by splice() method.

function removeByValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}

The above code can be written as part of array also:

Example:

test = new Array();
Array.prototype.removeByValue = function(val) {
    for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
test.removeByValue('Cat');
alert("Array after removing elements: "+test);
 
Leave a comment

Posted by on July 4, 2012 in General, Javascript

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: