Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 519
Ajinkya Avatar asked Feb 24 '12 03:02

Ajinkya


3 Answers

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.

like image 98
nnnnnn Avatar answered Oct 16 '22 10:10

nnnnnn


I suggest you use Array.prototype.filter

var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
     return removeValFrom.indexOf(index) == -1;
})
like image 45
Sasha Davydenko Avatar answered Oct 16 '22 12:10

Sasha Davydenko


Here is one that I use when not going with lodash/underscore:

while(IndexesToBeRemoved.length) {
    elements.splice(IndexesToBeRemoved.pop(), 1);
}
like image 35
Dan Ochiana Avatar answered Oct 16 '22 11:10

Dan Ochiana