What is the in-place alternative to Array.prototype.filter()

后端 未结 6 1320
面向向阳花
面向向阳花 2020-11-29 07:37

I\'ve got an array that I would like to remove some elements from. I can\'t use Array.prototype.filter(), because I want to modify the array in place (because i

6条回答
  •  情书的邮戳
    2020-11-29 08:08

    A slightly simplified TypeScript variant of user663031's answer:

    function filter_in_place(array: Array, condition: (value: T) => boolean)
    {
        let next_place = 0;
    
        for (let value of array)
        {
            if (condition(value))
                array[next_place++] = value;
        }
    
        array.splice(next_place);
    }
    

    Using splice() instead of setting the length results in a 1.2x speedup for 1400000 iterations on Chrome 76.

提交回复
热议问题