Javascript Array remove(number)

Description

Javascript Array remove(number)


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

Array.prototype.remove = function (number) {
    for (var index = 0; index < this.length; index++) {
        if (this[index] == number) {
            this.splice(index, 1)//  www .j  a v  a2s.  com
        }
    }
   return this;
};

function start() {
    arr.remove(1);
    jsConsole.writeLine(arr);
    
}

Javascript Array remove(number)

/* Write a function that removes all elements with a given value
 * Attach it to the array type//  ww  w. j a  va  2  s .  co m
 * Read about prototype and how to attach methods  */
function run() {
    var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, "1"];
    jsConsole.writeLine("The initial array: " + arr);
    arr.remove(1); //arr = [2,4,3,4,111,3,2,"1"];
    jsConsole.writeLine("The array with the number 1 removed: " + arr);
}

Array.prototype.remove = function (number) {
    for (var i = 0; i < this.length; i++) {
        if (number === this[i]) {
            this.splice(i, 1);
        }
    }
};

Javascript Array remove(number)

/* Problem 2. Remove elements

 Write a function that removes all elements with a given value.
 Attach it to the array type./*  ww  w .ja v a  2  s .c o m*/

 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 example = [1, 4, 5, 3, 6, 4, 7, 3, 2];

Array.prototype.remove = function(number){
    var editedArray = [],
        index;

    for (index = 0; index < this.length; index += 1) {
        if (this[index] != number) {
            editedArray.push(this[index]);
        }
    }

    return editedArray;
};

console.log(example);
console.log(example.remove(4));

Javascript Array remove(number)

//  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
//  Read about prototype and how to attach methods
var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, "1"];
console.log('Original array');
console.log(arr);/*from w ww .  ja  v  a 2 s .  c o m*/

Array.prototype.remove = function (number) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == number) {
            this.splice(i, 1);
            i--;
        }
    }
}
console.log('Array after arr.remove(1)');
arr.remove(1);
console.log(arr);



PreviousNext

Related