Remove multiple elements from array in Javascript/jQuery

后端 未结 22 2112
梦毁少年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条回答
  •  -上瘾入骨i
    2021-01-29 20:33

    For Multiple items or unique item:

    I suggest you use Array.prototype.filter

    Don't ever use indexOf if you already know the index!:

    var valuesArr = ["v1","v2","v3","v4","v5"];
    var removeValFrom = [0, 2, 4];
    
    valuesArr = valuesArr.filter(function(value, index) {
         return removeValFrom.indexOf(index) == -1;
    }); // BIG O(N*m) where N is length of valuesArr and m is length removeValFrom
    

    Do:

    with Hashes... using Array.prototype.map

      var valuesArr = ["v1","v2","v3","v4","v5"];
      var removeValFrom = {};
      ([0, 2, 4]).map(x=>removeValFrom[x]=1); //bild the hash.
      valuesArr = valuesArr.filter(function(value, index) {
          return removeValFrom[index] == 1;
      }); // BIG O(N) where N is valuesArr;
    

提交回复
热议问题