Javascript Array removeValue(value) method

Description

Javascript Array removeValue(value) method


Array.prototype.removeValue = function (value) {
 var index = -1;/*from  ww w . j  a  v  a  2s . c  om*/
 for (var i = 0; i < this.length; i++) {
  if (this[i] == value) {
   this.splice(i,1);
   index = i;
  }
 }
 return index;
}

Javascript Array removeValue(value)

//Problem 2. Remove elements
////from w w  w  . j  a  va  2  s . co m
//Write a function that removes all elements with a given value.
//    Attach it to the array type.
//    Read about prototype and how to attach methods.
//
//    var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1'];
//    arr.remove(1); //arr = [2,4,3,4,111,3,2,'1'];

var i,
    len,
    arr = [1, 2, 1, 4, 1, 1, 3, 4, 1, 111, 3, 2, 1, '1'];

Array.prototype.removeValue = function(value) {

    for (i = 0, len = this.length; i < len; i += 1) {
        if (this[i] === value) {
            this.splice(i, 1);
            i -= 1;
        }
    }
}

arr.removeValue(1);
console.log(arr.join(','));



PreviousNext

Related