1

I am trying to splice all instances of some defined value from an array.

    filterfunc: function(anyArray){
      for(var i = 0; i <anyArray.length; i++){
        var v = anyArray[i];
          for(var j = 1; j <arguments.length; j++){
           if(v == arguments[j]){
              anyArray.splice(i,1);
            }
          }
        } 
          return anyArray;
      },

I pass an array along with the arguments that I don't want.

The problem I encounter is that the splice function does not splice all instances of the value.

ex: filterfunc([1,2,2,2,3,3,3,4,5,6],2,3); the result: [1,2,3,3,4,5,6]

I want it to return [1,4,5,6]

2
  • What criteria are you using to decide if you remove a value from an array or not? Commented Mar 3, 2013 at 19:57
  • if the array passed "anyArray" contains anyone of the other arguments passed. So I increment through anyArray checking if any element is the same as the arguments[j] Commented Mar 3, 2013 at 20:01

8 Answers 8

4

I'm not good in JavaScript, but deleting array items decrease their size and in such case is good to loop through in backward order.

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

Comments

2

I would instead send a second array such as: filterfunc([1,2,2,2,3,3,3,4,5,6],[2,3]) and use Array.prototype.filter():

function filterfunc(a, b) {
  return a.filter(function(x) { return b.indexOf(x) == -1; });
}

Comments

1

Add an i-- after you splice otherwise the string will shorten and then you will miss out values to be considered:

http://jsfiddle.net/6HatJ/1/

function filterfunc(anyArray){
  for(var i = 0; i <anyArray.length; i++){
    var v = anyArray[i];
      for(var j = 1; j <arguments.length; j++){
       if(v == arguments[j]){
          anyArray.splice(i,1);
           i--;
        }
      }
    } 
      return anyArray;
  };

1 Comment

note that you're adding "var" here as if it's block scoped, whereas JS is function scoped. Move all those var declarations to outside of the loops (var i,v,j; for(i=...) etc. =).
0

Underscore contains alot of useful helper functions and uniq might be just what you are looking for.

If you just want that function and not the entire library you´d just have a look at the source code.

1 Comment

I do not want to use underscore.js
0

anyArray.splice(...) changes the number of elements in the array and therefore the indexes of the existing ones. You should decrease index by one each time you delete an element

anyArray.splice(i--,1);

Comments

0

Let's use forEach, and also observe that splice is an in-place function. Returning the array just gives us a reference that we already had:

function remove(arr,elements) {
  elements.forEach(function(e) {
    for(var i=arr.length-1; i>=0; i--) {
      if(arr[i]==e) { arr.splice(i,1); }
    }
  });
}

// test
var a = [1,2,3,3,3,3,4,5,5,6,7,7],
    b  = [3,5,7];
remove(a,b);
a;

Comments

0

How about a while loop.

function removeInstanceOfElement(elem, arr)
{
    var index = 0;

    while(index < arr.length)
    {
        if(arr[index] == elem)
        {
            arr.splice(index, 1);
            index = 0;
        }
        else
        {
            ++index;
        }
    }

    return arr;
}

Comments

0

You could use reduce to go through the array with splice. Here is a simple example using splice with reduce

Say we have an array a and want to remove all instances of 'd'

a = ['a', 'b', 'd', 'c', 'd'];
a.reduce((prevValReturned, currVal, currIndex, array) =>{
  if (currVal == 'd') a.splice(currIndex, 1);
}, 0);

Viewing the array a in the console you see that it is now

["a", "b", "c"]

However splice is order n on each call, shifting all successive elements. If working with very large data set might be better to just loop through and use push

a = ['a', 'b', 'd', 'c', 'd'];
b= []
a.reduce((prevValReturned, currVal, currIndex, array) =>{
  if (currVal != 'd') b.push(currVal);
}, 0)

Of course this does not mutate array a. Viewing array b in the console you see

["a", "b", "c"]

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.