83

I have an array of elements and need to remove certain ones from it. The problem is that JavaScript doesn't seem to have a for each loop and if I use a for loop I run into problems with it basically trying to check elements beyond the bounds of the array, or missing elements in the array because the indexes change. Let me show you what I mean:

var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = 0; i < elements.length; i++){
    if(elements[i] == 5){
        elements.splice(i, 1);
    }
}

The problem is that when elements[1] is removed, elements[2] becomes elements[1]. So first problem is that some elements are never examined. The other problem is that .length changes and if I hard code the bounds, then I might be trying to examine elements beyond the bounds of the array. So what's the best way to do this incredibly simple thing?

Captain Stack
  • 3,572
  • 5
  • 31
  • 56

6 Answers6

199

Start from the top!

var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = elements.length - 1; i >= 0; i--){
    if(elements[i] == 5){
        elements.splice(i, 1);
    }
}
Aiq0
  • 306
  • 1
  • 11
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
38

You could use the filter method here:

var elements = [1, 5, 5, 3, 5, 2, 4].filter(function(a){return a !== 5;});
//=> elements now [1,3,2,4]

Or if you don't want to touch elements:

var elementsfiltered
   ,elements = [1, 5, 5, 3, 5, 2, 4]
                .filter( function(a){if (a!==5) this.push(a); return true;},
                         elementsfiltered = [] );
   //=> elementsfiltered = [1,3,2,4], elements = [1, 5, 5, 3, 5, 2, 4]

See MDN documentation for filter

Alternatively you can extend the Array.prototype

Array.prototype.remove = Array.prototype.remove || function(val){
    var i = this.length;
    while(i--){
        if (this[i] === val){
            this.splice(i,1);
        }
    }
};
var elements = [1, 5, 5, 3, 5, 2, 4];
elements.remove(5);
//=> elements now [1,3,2,4]
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    While creating a new array, which filter does, is not a bad suggestion as a solution, the OP does actually ask about removing elements inline and it would seem best to give an example of that. – Xotic750 May 03 '13 at 06:20
  • 1
    Seems like an unnecessary departure from the original code. OP could keep his existing code by decrementing `i` after the splice. – Dagg Nabbit May 03 '13 at 06:41
  • personally I feel filter is safer as decrementing i may lead to edge cases as if zero elements are there etc – sktguha Mar 28 '17 at 16:17
10

var elements = [1, 5, 5, 3, 5, 2, 4];    
var i = elements.length;
while (i--) {
    if (elements[i] == 5) {
        elements.splice(i, 1);
    }
}
console.log(elements);
rouble
  • 16,364
  • 16
  • 107
  • 102
2

You could simply decrement i whenever you remove an item.

var elements = [1, 5, 5, 3, 5, 2, 4];

var l = elements.length;
for(var i = 0; i < l; i++){
    if(elements[i] == 5){
        elements.splice(i, 1);
        i--;
    }
}

console.log(elements);
Lachmanski
  • 111
  • 3
  • 5
1

Using Array.shift():

var array = [1, 2, 3, 'a', 'b', 'c'];
while (array.length > 0) {
  console.log(array.shift());
}

Edit: Probably does not suit the specs. I misread the question (only remove certain elements) and was too eager instead to add a method that was not mentioned yet...

Geert
  • 3,527
  • 1
  • 20
  • 16
  • 3
    As you say in your edit, this doesn't actually answer the question, however it does answer the question I was trying to search for. Thank you. – spikyjt Sep 09 '16 at 14:10
0

This is an example of using Array.indexOf, while and Array.splice to remove elements inline.

var elements = [1, 5, 5, 3, 5, 2, 4];
var remove = 5;
var index = elements.indexOf(remove);

while (index !== -1) {
    elements.splice(index, 1);
    index = elements.indexOf(remove);
}

console.log(elements);

On jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • 2
    downvoted for inefficient O(n^2) algorithm – Alnitak Sep 25 '14 at 13:23
  • I never made any claims on efficiency, and the question didn't concern that, but how you can deal with a changing array length when performing inline element removal. Here is a jsPerf so that you can give your efficient version as an answer and compare it with other answers posted. http://jsperf.com/soq-iterate-over-an-array-and-remove – Xotic750 Sep 26 '14 at 20:12
  • the canonical method of dealing with a changing array length is to start from the end of the array and work backwards. Alternatively it's possible to work forwards _from the current position_ and not increment if you've removed the current element. Instead, your method _starts over from the zeroth element_ every time a match is found, thereby repeatedly going over and over the same elements. It's a very poor algorithm and shouldn't ever be used. – Alnitak Sep 27 '14 at 06:45
  • And yet this ECMA5 method is super fast on the most current version of Chrome, and other browsers are bound to catch up, faster than the accepted answer on the small sample provided. – Xotic750 Sep 27 '14 at 19:38
  • If you had used the `fromIndex` parameter to `.indexOf()` I would have no complaint - that would make it `O(n)` instead of `O(n^2)`. At the moment it only wins (on short arrays) because it's using a compiled built-in to scan the array instead of a hand-written loop. In fact if you had done this you'd actually have the best answer here. – Alnitak Sep 28 '14 at 06:31
  • 1
    OK, that's weird - I tried that and (on this small sample set) it was substantially slower. I don't know why yet. http://jsperf.com/soq-iterate-over-an-array-and-remove/2 – Alnitak Sep 28 '14 at 06:58
  • Personally, I would usually use the method shown in the accepted answer, and that is why I also voted for it. But interesting results. – Xotic750 Sep 28 '14 at 10:29
  • 1
    I changed the test case slightly - now the fromIndex case runs _very slightly_ faster... http://jsperf.com/soq-iterate-over-an-array-and-remove/3 – Alnitak Sep 29 '14 at 17:39
  • I guess (not tested) that it will make more of a difference on a larger set of data, and it is still only fastest on Chrome (with this small data set) and so using the reverse loop gives better cross browser performance. Feel free to improve my answer, if you feel like it. :) – Xotic750 Sep 29 '14 at 20:12
  • Downvoted for "I never made any claims on efficiency, and the question didn't concern that". – Don Hatch Jun 29 '19 at 21:50
  • @Alnitak, no, using the fromIndex parameter will not fix this algorithm's quadratic behavior. – Don Hatch Jun 29 '19 at 22:24
  • @DonHatch Are you alluding to the removal operation itself being something other than O(1) ? The point of using `fromIndex` is that it prevents the scan from considering the entire array from the start each time. – Alnitak Jun 30 '19 at 09:11
  • @Alnitak, right, the removal isn't O(1). – Don Hatch Jun 30 '19 at 09:15
  • @DonHatch well, it might be, but that's implementation dependent. If the removal is itself O(n) then the original algorithm here would be O(n^3) – Alnitak Jun 30 '19 at 13:48
  • @Alnitak, no, it's not implementation dependent; think about how many items the splice() has to move, in order to make them look-up-able in O(1) time afterwards. And no, that doesn't make the overall algorithm O(n^3); there are O(n) splices taking O(n) time, contributing O(n)*O(n) = O(n^2) to the overall time. – Don Hatch Jun 30 '19 at 15:29