Javascript Array remove(valueToRemove)

Description

Javascript Array remove(valueToRemove)


/*Task 02. Write a function that removes all elements with a given value:
 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'];
 Attach it to the array type//from w w  w.  jav a 2s  .  c  o  m
 Read about prototype and how to attach methods */

Array.prototype.remove = function (valueToRemove) {
    while(this.indexOf(valueToRemove) !== -1) {
        var index = this.indexOf(valueToRemove);
        this.splice(index, 1);
    }

    return this;
};
var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1'];
arr.remove(1);

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



PreviousNext

Related