JavaScript method to remove a specified value element from an array

  • 2020-05-17 04:47:21
  • OfStack

This example shows how JavaScript removes elements of a specified value from an array. Share with you for your reference. The specific analysis is as follows:

The following code deletes the elements of an array in two ways. The first defines a single function, and the second defines an removeByValue method for the Array object. The call is simple

Define the function removeByValue for element deletion


function removeByValue(arr, val) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] == val) {
      arr.splice(i, 1);
      break;
    }
  }
}
var somearray = ["mon", "tue", "wed", "thur"]
removeByValue(somearray, "tue");
//somearray will now have "mon", "wed", "thur"

Adding a method to the array object makes the call easier, and the removeByValue method of the array is called directly to delete the specified element


Array.prototype.removeByValue = function(val) {
  for(var i=0; i<this.length; i++) {
    if(this[i] == val) {
      this.splice(i, 1);
      break;
    }
  }
}
var somearray = ["mon", "tue", "wed", "thur"]
somearray.removeByValue("tue");
//somearray will now have "mon", "wed", "thur"

I hope this article is helpful to you in javascript programming.


Related articles: