Javascript Array removeAll(element)

Description

Javascript Array removeAll(element)


// 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


Array.prototype.removeAll = function (element) {
    var newArr = [];
    for (var i in this) {
        if (this[i] != element) {
            newArr.push(this[i]);/*w  w  w .  jav a2  s  .c om*/
        }
    }
    return newArr;
}

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

var finalArr = arr.removeAll(1);

for (var i in finalArr) {
    console.log(finalArr[i]);
}

Javascript Array removeAll(element)

//Problem 2/*from w  w  w  .  ja va 2  s. c  om*/
var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1'];

Array.prototype.removeAll = function (element){
    var i,
        length = this.length;

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

    }
}

console.log('Problem 2:');
arr.removeAll(1);
console.log('Result:');
console.log(arr);
console.log('\n');

Javascript Array removeAll(element)

/*Problem 2. Remove elements

 Write a function that removes all elements with a given value.
 Attach it to the array type.//from  ww w . j ava  2 s.  co  m
 Read about prototype and how to attach methods.
 */

// Use Node.js to test solution
Array.prototype.removeAll = function (element) {
    var len,
        i;

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

    return this;
};

// Example from problem
var someArray = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1'];
console.log(someArray.removeAll(1));

Javascript Array removeAll(element)

Array.prototype.removeAll = function (element) {
    var i,/*from www . ja v a2s.c  o  m*/
        len = this.length,
        result = [],
        count = 0;
    for (i = 0; i < len; i += 1) {
        if (this[i] != element) {
            result[count] = this[i];
            count = count + 1;
        }
    }
    return result;
};



PreviousNext

Related