Remove multiple elements from array in Javascript/jQuery

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

    If you are using underscore.js, you can use _.filter() to solve your problem.

    var valuesArr = new Array("v1","v2","v3","v4","v5");
    var removeValFromIndex = new Array(0,2,4);
    var filteredArr = _.filter(valuesArr, function(item, index){
                      return !_.contains(removeValFromIndex, index);
                    });
    

    Additionally, if you are trying to remove items using a list of items instead of indexes, you can simply use _.without(), like so:

    var valuesArr = new Array("v1","v2","v3","v4","v5");
    var filteredArr = _.without(valuesArr, "V1", "V3");
    

    Now filteredArr should be ["V2", "V4", "V5"]

    0 讨论(0)
  • 2021-01-29 20:35

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

    while(IndexesToBeRemoved.length) {
        elements.splice(IndexesToBeRemoved.pop(), 1);
    }
    
    0 讨论(0)
  • 2021-01-29 20:35
    removeValFromIndex.forEach(function(toRemoveIndex){
        valuesArr.splice(toRemoveIndex,1);
    });
    
    0 讨论(0)
  • 2021-01-29 20:36

    A simple and efficient (linear complexity) solution using filter and Set:

    const valuesArr = ['v1', 'v2', 'v3', 'v4', 'v5'];   
    const removeValFromIndex = [0, 2, 4];
    
    const indexSet = new Set(removeValFromIndex);
    
    const arrayWithValuesRemoved = valuesArr.filter((value, i) => !indexSet.has(i));
    
    console.log(arrayWithValuesRemoved);

    The great advantage of that implementation is that the Set lookup operation (has function) takes a constant time, being faster than nevace's answer, for example.

    0 讨论(0)
  • 2021-01-29 20:38

    In pure JS you can loop through the array backwards, so splice() will not mess up indices of the elements next in the loop:

    for (var i = arr.length - 1; i >= 0; i--) {
        if ( yuck(arr[i]) ) {
            arr.splice(i, 1);
        }
    }
    
    0 讨论(0)
  • 2021-01-29 20:40

    Here's one possibility:

    valuesArr = removeValFromIndex.reduceRight(function (arr, it) {
        arr.splice(it, 1);
        return arr;
    }, valuesArr.sort(function (a, b) { return b - a }));
    

    Example on jsFiddle

    MDN on Array.prototype.reduceRight

    0 讨论(0)
提交回复
热议问题