Remove multiple elements from array in Javascript/jQuery

后端 未结 22 2108
梦毁少年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:33

    A simple solution using ES5. This seems more appropriate for most applications nowadays, since many do no longer want to rely on jQuery etc.

    When the indexes to be removed are sorted in ascending order:

    var valuesArr = ["v1", "v2", "v3", "v4", "v5"];   
    var removeValFromIndex = [0, 2, 4]; // ascending
    
    removeValFromIndex.reverse().forEach(function(index) {
      valuesArr.splice(index, 1);
    });
    

    When the indexes to be removed are not sorted:

    var valuesArr = ["v1", "v2", "v3", "v4", "v5"];   
    var removeValFromIndex = [2, 4, 0];  // unsorted
    
    removeValFromIndex.sort(function(a, b) { return b - a; }).forEach(function(index) {
      valuesArr.splice(index, 1);
    });
    

提交回复
热议问题