Remove an item from array using UnderscoreJS

后端 未结 11 2133
一向
一向 2020-12-04 06:02

Say I have this code

var arr = [{id:1,name:\'a\'},{id:2,name:\'b\'},{id:3,name:\'c\'}];

and I want to remove the item with id = 3 from the array. Is th

相关标签:
11条回答
  • 2020-12-04 06:26

    You can use reject method of Underscore, below will return a new array which won't have array with particular match

    arr = _.reject(arr, function(objArr){ return objArr.id == 3; });
    
    0 讨论(0)
  • 2020-12-04 06:28

    Use Underscore _.reject():

    arr = _.reject(arr, function(d){ return d.id === 3; });
    
    0 讨论(0)
  • 2020-12-04 06:29

    or another handy way:

    _.omit(arr, _.findWhere(arr, {id: 3}));
    

    my 2 cents

    0 讨论(0)
  • 2020-12-04 06:36

    Other answers create a new copy of the array, if you want to modify the array in place you can use:

    arr.splice(_.findIndex(arr, { id: 3 }), 1);
    

    But that assumes that the element will always be found inside the array (because if is not found it will still remove the last element). To be safe you can use:

    var index = _.findIndex(arr, { id: 3 });
    if (index > -1) {
        arr.splice(index, 1);
    }
    
    0 讨论(0)
  • 2020-12-04 06:37

    Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.

    Returns a copy of the array with all instances of the values removed.

    _.without(["bob", "sam", "fred"], "sam");
    
    => ["bob", "fred"]
    

    Works with more complex objects too.

    var bob = { Name: "Bob", Age: 35 };
    var sam = { Name: "Sam", Age: 19 };
    var fred = { Name: "Fred", Age: 50 };
    
    var people = [bob, sam, fred]
    
    _.without(people, sam);
    
    => [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];
    

    If you don't have the item to remove, just a property of it, you can use _.findWhere and then _.without.

    0 讨论(0)
提交回复
热议问题