Remove an item from array using UnderscoreJS

后端 未结 11 2209
一向
一向 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: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);
    }
    

提交回复
热议问题