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

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

    What you could use

    • filter returns an array with the same elements, but not necesserily all.
    • map returns something for each loop, the result is an array with the same length as the source array
    • forEach returns nothing, but every element is processes, like above.
    • reduce returns what ever you want.
    • some/every returns a boolean value

    But nothing from above is mutilating the original array in question of length in situ.

    I suggest to use a while loop, beginning from the last element and apply splice to the element, you want to remove.

    This keeps the index valid and allows to decrement for every loop.

    Example:

    var array = [0, 1, 2, 3, 4, 5],
        i = array.length;
    
    while (i--) {
        if (array[i] % 2) {
            array.splice(i, 1);
        }
    }
    console.log(array);

提交回复
热议问题