Remove multiple elements from array in Javascript/jQuery

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

    var valuesArr = new Array("v1","v2","v3","v4","v5");   
    var removeValFromIndex = new Array(0,2,4);
    
    console.log(valuesArr)
    let arr2 = [];
    
    for (let i = 0; i < valuesArr.length; i++){
      if (    //could also just imput this below instead of index value
        valuesArr[i] !== valuesArr[0] && // "v1" <--
        valuesArr[i] !== valuesArr[2] && // "v3" <--
        valuesArr[i] !== valuesArr[4]    // "v5" <--
      ){
        arr2.push(valuesArr[i]);
      }
    }
    
    console.log(arr2);
    

    This works. However, you would make a new array in the process. Not sure if thats would you want or not, but technically it would be an array containing only the values you wanted.

提交回复
热议问题