29

I have an array like this :

var array = [1,20,50,60,78,90];
var id = 50;

How can i remove the id from the array and return a new array that does not have the value of the id in new array?

4

3 回答 3

46

对于复杂的解决方案,您可以使用 method _.reject(),以便您可以将自定义逻辑放入回调:

var removeValue = function(array, id) {
    return _.reject(array, function(item) {
        return item === id; // or some complex logic
    });
};
var array = [1, 20, 50, 60, 78, 90];
var id = 50;
console.log(removeValue(array, id));

对于简单的情况,使用更方便的方法_.without()

var array = [1, 20, 50, 60, 78, 90];
var id = 50;
console.log(_.without(array, id));

演示

于 2013-10-08T08:19:18.363 回答
14

_filter也可以。这与_reject相反。

var array = [1,20,50,60,78,90];
var id = 50;

var result = _.filter(array, function(x) { return x != id });

http://jsfiddle.net/kman007_us/WzaJz/5/

于 2014-06-01T02:49:10.263 回答
1

您可以使用splice,尽管它不是下划线的 API:

arrayObject.splice(index,howmany,item1,.....,itemX)

在您的示例中:

var index = _.indexOf(array, id);
array.splice(index, 1);
于 2016-06-20T09:45:53.463 回答