2

I was trying to remove some items from an array ,

Array.prototype.remove = function(from, to)
{
      var rest = this.slice((to || from) + 1 || this.length);
     this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
};

var BOM = [0,1,0,1,0,1,1];


var IDLEN = BOM.length;

for(var i = 0; i < IDLEN ;++i)
{

     if( BOM[i] == 1) 
     {
         BOM.remove(i);
     //IDLEN--;
     }

} 

RESULT IS

   BOM = [0,0,0,1];

expected result is

   BOM = [0,0,0];

its looks like i am doing something wrong , Please help me.

Thanks.

3
  • Can you at least describe how this works? What is the criteria of removal? Commented Nov 6, 2012 at 5:02
  • When is your IDLEN defined? Also, your remove method seems familiar to Array.splice, have you consider using it to accomplish what you want? Commented Nov 6, 2012 at 5:03
  • sorry , question edited. Commented Nov 6, 2012 at 5:04

3 Answers 3

4

try this

var BOM = [0,1,0,1,0,1,1];
for(var i = 0; i < BOM.length;i++){
  if( BOM[i] == 1) {
     BOM.splice(i,1); 
     i--;
  }
} 
console.log(BOM);
Sign up to request clarification or add additional context in comments.

Comments

1
Try using filter:    

var test1 = ['a','b','c','d'];
var test2 = ['b','c'];

test2.forEach(removeItem => 
{
  test1 = test1.filter(item => item != removeItem);
})

console.log('Modified array',test1);

Comments

0
Array.prototype.remove= function(){
    var what, a= arguments, L= a.length, ax;
    while(L && this.length){
        what= a[--L];
        while((ax= this.indexOf(what))!= -1){
            this.splice(ax, 1);
        }
    }
    return this;
}

Call this function

for(var i = 0; i < BOM.length; i++)
{
    if(BOM[i] === 1) 
      BOM.remove(BOM[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.