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

后端 未结 6 1312
面向向阳花
面向向阳花 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 07:49

    The currently selected answer works perfectly fine. However, I wanted this function to be a part of the Array prototype.

    Array.prototype.filterInPlace = function(condition, thisArg) {
        let j = 0;
    
        this.forEach((el, index) => {
            if (condition.call(thisArg, el, index, this)) {
                if (index !== j) {
                    this[j] = el;
                }
                j++;
            }
        })
    
        this.length = j;
        return this;
    }
    

    With this I can just call the function like so:

    const arr = [1, 2, 3, 4];
    arr.filterInPlace(x => x > 2);
    // [1, 2]
    

    I just keep this in a file called Array.js and require it when needed.

提交回复
热议问题