The best way to remove array element by value

后端 未结 10 1326
北荒
北荒 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:35

    There is an underscore method for this, http://underscorejs.org/#without

    arr = ["orange","red","black","white"];
    
    arr = _.without(arr, "red");
    
    0 讨论(0)
  • 2020-12-25 10:41

    Here's how it's done:

    var arr = ["orange","red","black","white"];
    var index = arr.indexOf("red");
    if (index >= 0) {
      arr.splice( index, 1 );
    }
    

    This code will remove 1 occurency of "red" in your Array.

    0 讨论(0)
  • 2020-12-25 10:43

    If order the array (changing positions) won't be a problem you can solve like:

    var arr = ["orange","red","black","white"];
    arr.remove = function ( item ) {
      delete arr[item];
      arr.sort();
      arr.pop();
      console.log(arr);
    }
    
    arr.remove('red');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 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");
    
    0 讨论(0)
提交回复
热议问题