Say I have this code
var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
and I want to remove the item with id = 3 from the array. Is there a way of doing this without splicing? Maye something using underscore or something like that?
Thanks!
Use Underscore
_.reject()
:Other answers create a new copy of the array, if you want to modify the array in place you can use:
But that assumes that the element will always be found inside the array (because if is not found it will still remove the last element). To be safe you can use:
Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.
Works with more complex objects too.
If you don't have the item to remove, just a property of it, you can use
_.findWhere
and then_.without
.Please exercise care if you are filtering strings and looking for case insensitive filters. _.without() is case sensitive. You can also use _.reject() as shown below.
Use can use plain JavaScript's
Array#filter
method like this:Or, use
Array#reduce
andArray#concat
methods like this:NOTE:
or another handy way:
my 2 cents