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:

Leave a Reply