Removing Item from array with Underscore.js

后端 未结 3 393
不思量自难忘°
不思量自难忘° 2021-01-01 10:17

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 tha

3条回答
  •  遥遥无期
    2021-01-01 10:58

    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

提交回复
热议问题