The best way to remove array element by value

后端 未结 10 1345
北荒
北荒 2020-12-25 10:18

I have an array like this

arr = [\"orange\",\"red\",\"black\",\"white\"]

I want to augment the array object defining a deleteElem()<

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 10:47

    Back when I was new to coding I could hardly tell what splice was doing, and even today it feels less readable.

    But readability counts.

    I would rather use the filter method like so:

    arr = ["orange","red","black","white","red"]
    
    arr = arr.filter(val => val !== "red");
    
    console.log(arr) // ["orange","black","white"]
    

    Note how all occurrences of "red" are removed from the array.

    From there, you can easily work with more complex data such as array of objects.

    arr = arr.filter(obj => obj.prop !== "red");
    

提交回复
热议问题