Removing Item from array with Underscore.js

2019-02-07 17:41发布

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?

3条回答
forever°为你锁心
2楼-- · 2019-02-07 18:13

_filter works too. It's the opposite of _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/

查看更多
smile是对你的礼貌
3楼-- · 2019-02-07 18:26

You can use splice, though it is not underscore's API:

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

In your example:

var index = _.indexOf(array, id);
array.splice(index, 1);
查看更多
戒情不戒烟
4楼-- · 2019-02-07 18:37

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));

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));

DEMO

查看更多
登录 后发表回答