Javascript Array remove(x)

Description

Javascript Array remove(x)

Array.prototype.remove = function (x) {
  var keepers = [];

  for (var i = 0; i < this.length; i += 1) {
    if (this[i] !== x) {
      keepers.push(this[i]);// w  w w . jav  a  2s  .c om
    }
  }

  return keepers;
};

Javascript Array remove(x)

'use strict';//from   w  w w  . j  a v a2s.c  o  m

var someArray = [1, 2, 3];
// someArray.remove(1);
Array.prototype.remove = function(x) {
  for(let i = 0; i < this.length; i++) {
    if(this[i] === x) {this.splice(i, 1);}
  }
  return this;
};

someArray.remove(2);

Javascript Array remove(x)

Array.prototype.remove = function(x){
 this.splice(this.indexOf(x), 1);/*from  w w w .j av a  2s  .c  om*/
}

function clone(object){
 var c = {};
 for(var attribute in object){
  c[attribute] = object[attribute];
 }
 return c;
}

function randomSign(){
 if(Math.random() < .5){
  return -1;
 }
 return 1;
}

Javascript Array remove(x)

// test for array remove
// note: array.remove does not exist in the JavaScript standard
Array.prototype.remove = function(x) { 
  var idx = this.indexOf(x);
  if (idx<0) return; // not in array
  var l = this.length;
  for (var i=idx+1;i<l;i++)
    this[i-1]=this[i];//from  www . ja va 2  s. c o m
  this.pop(); // pop off the old value
} 

var a = [1,2,4,5,7];

a.remove(2);
a.remove(5);

result = a.length==3 && a[0]==1 && a[1]==4 && a[2]==7;

Javascript Array remove(x)

// 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'];

Array.prototype.remove = function(x) {
    var i;/*  w  w w .j a  v  a 2  s .  co m*/
    for (i = 0; i < this.length; i += 1) {
        if (this[i] === x) {
            this.splice(i, 1);
            i -= 1;
        }
    }
}


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

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



PreviousNext

Related