使用Underscore.js从数组中删除Item

MBe*_*mam 29 javascript underscore.js

我有这样一个数组:

var array = [1,20,50,60,78,90];
var id = 50;
Run Code Online (Sandbox Code Playgroud)

如何从数组中删除id并返回一个新数组中没有id值的新数组?

Eug*_*nov 44

For the complex solutions you can use method _.reject(), so that you can put a custom logic into callback:

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));
Run Code Online (Sandbox Code Playgroud)

For the simple cases use more convenient method _.without():

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

DEMO


Kev*_*ith 14

_filter也有效.它与_reject相反.

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

var result = _.filter(array, function(x) { return x != id });
Run Code Online (Sandbox Code Playgroud)

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