Remove an item from array using UnderscoreJS

Javascriptunderscore.js

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

Just using plain JavaScript, this has been answered already: https://stackoverflow.com/q/16491758/218196.

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
}));
console.log(arr);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></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.

Solution 2 - Javascript

You can use Underscore .filter

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

    var filtered = _(arr).filter(function(item) {
         return item.id !== 3
    });

Can also be written as:

var filtered = arr.filter(function(item) {
    return item.id !== 3
});

var filtered = _.filter(arr, function(item) {
    return item.id !== 3
});

Check Fiddle

You can also use .reject

Solution 3 - Javascript

Use Underscore _.reject():

arr = _.reject(arr, function(d){ return d.id === 3; });

Solution 4 - Javascript

Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.

> Returns a copy of the array with all instances of the values removed.

_.without(["bob", "sam", "fred"], "sam");

=> ["bob", "fred"]

Works with more complex objects too.

var bob = { Name: "Bob", Age: 35 };
var sam = { Name: "Sam", Age: 19 };
var fred = { Name: "Fred", Age: 50 };

var people = [bob, sam, fred]

_.without(people, sam);

=> [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];

If you don't have the item to remove, just a property of it, you can use _.findWhere and then _.without.

Solution 5 - Javascript

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.

var arr = ["test","test1","test2"];

var filtered = _.filter(arr, function(arrItem) {
    return arrItem.toLowerCase() !== "TEST".toLowerCase();
});
console.log(filtered);
// ["test1", "test2"]

var filtered1 = _.without(arr,"TEST");
console.log(filtered1);
// ["test", "test1", "test2"]

var filtered2 = _.reject(arr, function(arrItem){ 
    return arrItem.toLowerCase() === "TEST".toLowerCase();
});
console.log(filtered2);
// ["test1", "test2"]

Solution 6 - Javascript

Other answers create a new copy of the array, if you want to modify the array in place you can use:

arr.splice(_.findIndex(arr, { id: 3 }), 1);

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:

var index = _.findIndex(arr, { id: 3 });
if (index > -1) {
    arr.splice(index, 1);
}

Solution 7 - Javascript

or another handy way:

_.omit(arr, _.findWhere(arr, {id: 3}));

my 2 cents

Solution 8 - Javascript

Use can use plain JavaScript's Array#filter method like this:

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

var filteredArr = arr.filter(obj => obj.id != 3);

console.log(filteredArr);

Or, use Array#reduce and Array#concat methods like this:

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

var reducedArr = arr.reduce((accumulator, currObj) => {
  return (currObj.id != 3) ? accumulator.concat(currObj) : accumulator;
}, []);

console.log(reducedArr);

NOTE:

  • Both of these are pure functional approach (i.e. they don't modify the existing array).
  • No, external library is required in these approach (Vanilla JavaScript is enough).

Solution 9 - Javascript

I used to try this method

_.filter(data, function(d) { return d.name != 'a' });

There might be better methods too like the above solutions provided by users

Solution 10 - Javascript

By Using underscore.js

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

var resultArr = _.reject(arr,{id:3});

console.log(resultArr);

The result will be :: [{id:1name:'a'},{id:2,name:'c'}]

Solution 11 - Javascript

You can use reject method of Underscore, below will return a new array which won't have array with particular match

arr = _.reject(arr, function(objArr){ return objArr.id == 3; });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclimboidView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptSushanth --View Answer on Stackoverflow
Solution 3 - JavascriptgreenafricanView Answer on Stackoverflow
Solution 4 - JavascriptPeteGOView Answer on Stackoverflow
Solution 5 - JavascriptSrihari SridharanView Answer on Stackoverflow
Solution 6 - JavascriptSajjad ShirazyView Answer on Stackoverflow
Solution 7 - JavascriptNadeemView Answer on Stackoverflow
Solution 8 - JavascriptBlackBeardView Answer on Stackoverflow
Solution 9 - JavascriptBastin RobinView Answer on Stackoverflow
Solution 10 - JavascriptAnand TamizhView Answer on Stackoverflow
Solution 11 - JavascriptSTEELView Answer on Stackoverflow