Remove multiple elements from array in Javascript/jQuery

后端 未结 22 2181
梦毁少年i
梦毁少年i 2021-01-29 19:42

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:

<
22条回答
  •  时光取名叫无心
    2021-01-29 20:25

    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.

提交回复
热议问题