Skip to content
Advertisement

Remove multiple elements from array in Javascript/jQuery

I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:

var valuesArr = new Array("v1","v2","v3","v4","v5");   
var removeValFromIndex = new Array(0,2,4);

I want to remove the values present at indices 0,2,4 from valuesArr. I thought the native splice method might help so I came up with:

$.each(removeValFromIndex,function(index,value){
    valuesArr.splice(value,1);
});

But it didn’t work because after each splice, the indices of the values in valuesArr were different. I could solve this problem by using a temporary array and copying all values to the second array, but I was wondering if there are any native methods to which we can pass multiple indices at which to remove values from an array.

I would prefer a jQuery solution. (Not sure if I can use grep here)

Advertisement

Answer

There’s always the plain old for loop:

var valuesArr = ["v1","v2","v3","v4","v5"],
    removeValFromIndex = [0,2,4];    

for (var i = removeValFromIndex.length -1; i >= 0; i--)
   valuesArr.splice(removeValFromIndex[i],1);

Go through removeValFromIndex in reverse order and you can .splice() without messing up the indexes of the yet-to-be-removed items.

Note in the above I’ve used the array-literal syntax with square brackets to declare the two arrays. This is the recommended syntax because new Array() use is potentially confusing given that it responds differently depending on how many parameters you pass in.

EDIT: Just saw your comment on another answer about the array of indexes not necessarily being in any particular order. If that’s the case just sort it into descending order before you start:

removeValFromIndex.sort(function(a,b){ return b - a; });

And follow that with whatever looping / $.each() / etc. method you like.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement