[Javascript] Remove item in Array

In Java and C#, it is common to use List to store collection and it can simply remove item by method remove() . However, there is no list in Javascript so it need to handle by own.

In Javascript, it can remove array item by method splice(). However, it only can remove by index but not value. Thus it need to create extension method by own.

/**
 * Remove array element(s) by value.
 * @param {Value to be remove} value 
 * @returns Array which removed value.
 */
Array.prototype.remove = function(value) {
    let index = 0;
    do {
      index = this.indexOf(value);
      if(index >=0)
        this.splice(index, 1);
    } while(index < 0)
}

Usage:

let months = ["Jan", "Feb","April","April", "March", "April", "May"];
console.log("Before run remove(): " + months);
months.remove('April');
console.log("After run remove(): " + months);

Output:

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.