1

I know it's very simple, but tried searching and could'nt find anything that would solve my problem.

So let's say I have this array:

 var chicken = [10, 45, 150, 5000, 25000, 100000, 150000];

and I want to remove everything except 25000. So I tried a simple iteration:

 for (var w=0; w<chicken.length; w++){
     if (chicken[w]<25000 || chicken[w]>25000){
    chicken.splice(w,1);
     }
 }

And it doesn't work. The output is [ 45, 5000, 25000, 150000 ], don't know why.

Hiago Serpa
  • 41
  • 1
  • 7

1 Answers1

8

The reason it doesn't work is because your array length is changing as you splice each item. If you want to loop and remove, use a reverse loop:

for (var i = chicken.length - 1; i >= 0; i--) {
    if (chicken[i] !== 25000) chicken.splice(i, 1);
}
tymeJV
  • 99,730
  • 13
  • 150
  • 152
  • Will this work with ranges too? For example ''I want to remove everything that is not between 20000 and 30000.'' With the 25000 as an example of the ||'s that need to be used. – Hiago Serpa Feb 25 '16 at 16:09
  • @HiagoSerpa Yes, just replace `if (chicken[i] !== 25000)` with `if (chicken[i] < 20000 || chicken[i] > 30000)` or any other filter – Matt Lishman Feb 25 '16 at 16:11
  • 1
    @HiagoSerpa -- Yeah - this will work with any kind of filtering from an array. The point was, when you remove, you change the length of the array, so eventually you'll get to an index that doesn't exist if you're counting up. – tymeJV Feb 25 '16 at 16:11