Remove multiple elements from array in Javascript/jQuery

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

    It feels necessary to post an answer with O(n) time :). The problem with the splice solution is that due to the underlying implementation of array being literally an array, each splice call will take O(n) time. This is most pronounced when we setup an example to exploit this behavior:

    var n = 100
    var xs = []
    for(var i=0; i=0;i--)
      is.push(i)
    

    This removes elements starting from the middle to the start, hence each remove forces the js engine to copy n/2 elements, we have (n/2)^2 copy operations in total which is quadratic.

    The splice solution (assuming is is already sorted in decreasing order to get rid of overheads) goes like this:

    for(var i=0; i

    However, it is not hard to implement a linear time solution, by re-constructing the array from scratch, using a mask to see if we copy elements or not (sort will push this to O(n)log(n)). The following is such an implementation (not that mask is boolean inverted for speed):

    var mask = new Array(xs.length)
    for(var i=is.length - 1; i>=0; i--)
      mask[is[i]] = true
    var offset = 0
    for(var i=0; i

    I ran this on jsperf.com and for even n=100 the splice method is a full 90% slower. For larger n this difference will be much greater.

提交回复
热议问题