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

后端 未结 6 1293
面向向阳花
面向向阳花 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:51

    You could use the following:

    array.splice(0, array.length,...array.filter(/*YOUR FUNCTION HERE*/))
    

    Explanation:

    • Splice acts in place
    • First argument means we start at the start of the array
    • Second means we delete the entire array
    • Third means we replace it with its filtered copy
    • The ... is the spread operator (ES6 only) and changes each member of the array into a separate argument

提交回复
热议问题