climboid climboid - 1 year ago 96
Javascript Question

Remove an item from array using UnderscoreJS

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?


Answer Source

Just using plain JavaScript, this has been answered already: remove objects from array by object property.

Using underscore.js, you could combine .findWhere with .without:

var arr = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'

//substract third
arr = _.without(arr, _.findWhere(arr, {
  id: 3
<script src=""></script>

Although, since you are creating a new array in this case anyway, you could simply use _.filter or the native Array.prototype.filter function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.

If you want to modify the array in-place, you have to use .splice. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download