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?
To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.
The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.
Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With