Remove multiple elements from array in Javascript/jQuery

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

提交回复
热议问题