Remove multiple elements from array in Javascript/jQuery

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

    Quick ES6 one liner:

    const valuesArr = new Array("v1","v2","v3","v4","v5");   
    const removeValFromIndex = new Array(0,2,4);
    
    const arrayWithValuesRemoved = valuesArr.filter((value, i) => removeValFromIndex.includes(i))
    
    0 讨论(0)
  • 2021-01-29 20:42

    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;
    })
    
    0 讨论(0)
  • 2021-01-29 20:46

    filter + indexOf (IE9+):

    function removeMany(array, indexes) {
      return array.filter(function(_, idx) {
        return indexes.indexOf(idx) === -1;
      });
    }); 
    

    Or with ES6 filter + find (Edge+):

    function removeMany(array, indexes = []) {
      return array.filter((_, idx) => indexes.indexOf(idx) === -1)
    }
    
    0 讨论(0)
  • 2021-01-29 20:46

    Here's a quickie.

    function removeFromArray(arr, toRemove){
        return arr.filter(item => toRemove.indexOf(item) === -1)
    }
    
    const arr1 = [1, 2, 3, 4, 5, 6, 7]
    const arr2 = removeFromArray(arr1, [2, 4, 6]) // [1,3,5,7]
    
    0 讨论(0)
提交回复
热议问题