Remove Element Javascript

How To Remove Element From Array in Javascript?

Every new release of JavaScript (JS) includes innovative functions to achieve common programming tasks. Some of the newer additions contain the Array indexOf() and DOM getElementsByClassName() functions. That being said, some browsers don’t keep up with the latest as well as greatest version of JavaScript or select to implement their own version of similar functionality.

To aid smooth things over, developers often rely on libraries such as jQuery, Dojo, and Mootools. As huge as these libraries are, there are times that you only need to beef up native JavaScript here and there. In those times, maybe you don’t require to load an entire library while you can just insert the missing functions yourself. In this article, we’ll look at how to exploit existing functionality to develop an Array utility function that eliminates elements by value.

Remove Element from Array in Javascript

One operation that seems to be trickier than it should be in every programming language is removing a value from an array.  It’s such a simple concept mentally that it skews our programmatic view of the task. In JavaScript the splice method is of huge aid to Remove Element From Array Javascript.

Building on Array.splice()

The Array.splice() purpose is the model behind the Array.remove() function that I’ll be presenting here. Array.splice() operates straight on an array and returns a new array of removed items, which are matched by index number. A second parameter denotes how many elements to eliminate. It might also be utilized to insert new items, however we won’t be making utilize of that feature here, so we’ll leave that part for another day.

Here’s an example of Array.splice() in action:

var cars = [“Buick”, “Camaro”, “Kia”, “Infiniti”];

var removedCars = cars.splice(2,2);

//After the above call, cars would be [“Buick”, “Camaro”]

//removedCars will contain “Kia” and “Infiniti”

Removing One Element

Our first interpretation behaves a lot like the Array.splice() function, however accepts an element value (object) instead of a numeric index. We could loop through the array, checking every element against our value, however there is previously a function that does exactly that; it’s called Array.indexOf() alike to the String function of the same name, the Array.indexOf() accepts a value as well as returns the numeric index of the first occurrence. Hence, if the array holds more than one instance of the same value, only the first index is returned. If no matches are searched, a value of -1 is returned. We may utilize that to only call Array.splice() when the array holds at least one instance of our search value. In the event that no matches are establish, an empty array is returned. I don’t like returning undefined variables from functions since it increases the likelihood of errors. jQuery takes the same approach.

if (!Array.prototype.remove) {

 Array.prototype.remove = function(val) {

   var i = this.indexOf(val);

        return i>-1 ? this.splice(i, 1) : [];

 };

}

var a = [1,2,3,2,4];

var removedItems = a.remove(2);          //a = [1,3,2,4], removedItems = [2];

var b = [1,2,3,2,4];

removedItems     = b.remove(8);    //b = [1,2,3,2,4], removedItems = [];

Removing Multiple Elements

One thing lacking from Array.indexOf() is the ability to search for multiple items at once, so if we wanted to support that usage, we’d have to employ our own looping mechanism. That’s where the 2nd version of Array.remove() comes in. This one accepts a second boolean parameter to specify that we want all occurrences of matching values. There are two very significant points to notice in the following for loop:

It goes backward. Otherwise, the index will access the wrong element after removing an item.

There is no checking clause. A funny thing concerning JS is that the loop will exit once the iterator counts down to zero.

if (!Array.prototype.remove) {

 Array.prototype.remove = function(val, all) {

   var i, removedItems = [];

   if (all) {

     for(i = this.length; i–;){

       if (this[i] === val) removedItems.push(this.splice(i, 1));

     }

   }

   else {  //same as before…

     i = this.indexOf(val);

     if(i>-1) removedItems = this.splice(i, 1);

   }

   return removedItems;

 };

}

var a = [1,2,3,2,4];

var removedItems = a.remove(2);             //a = [1,3,2,4], removedItems = [2];

var b = [1,2,3,2,4];

removedItems     = b.remove(2, true);        //b = [1,3,4], removedItems = [2,2];

How to Remove Elements from Middle of Array

The splice method can be utilized to add or remove elements from an array. The first argument specifies the location at which to begin addition or removing elements. The 2nd argument specifies the number of elements to eliminate. The third as well as subsequent arguments are optional; they identify elements to be added to the array.

Here we utilize the splice technique to remove two elements starting from position three:

var ar = [1, 2, 3, ‘a’, ‘b’, ‘c’]; // arguments: start position, number of elements to remove

console.log( ar.splice(3, 2) ); // [“a”, “b”]

console.log( ar ); // [1, 2, 3, “c”]

We utilize console.log to display the value returned, which is an array containing the removed elements. Then we utilize console.log to show the array after modification by our use of the splice method.

Leave a Comment

Your email address will not be published. Required fields are marked *