Remove multiple elements from array in Javascript/jQuery

后端 未结 22 2548
梦毁少年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"]

提交回复
热议问题