Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Item from array with Underscore.js

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?

like image 652
MBehtemam Avatar asked Oct 08 '13 08:10

MBehtemam


People also ask

How do you remove an item by ID in an 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.

What is _ each in JavaScript?

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.

Can you use underscore in JavaScript?

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.


1 Answers

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

like image 197
Eugene Naydenov Avatar answered Sep 20 '22 21:09

Eugene Naydenov