4

Why isn't there a super simple remove function in underscore?

var arr = [1,2,3,4,5];
_.remove(arr, 5);

Sure I could use reject or without... but neither of them are destructive. Am I missing something?

I guess I'll do it the old fashioned way...

arr.splice(arr.indexOf(5), 1);

ugh

savinger
  • 6,544
  • 9
  • 40
  • 57
  • So you need to modify the original, right? –  Aug 21 '13 at 16:42
  • possible duplicate of [remove item from array of objects in javascript](http://stackoverflow.com/questions/16994212/remove-item-from-array-of-objects-in-javascript) – Bergi Aug 21 '13 at 16:42

1 Answers1

13

Explanation

This is because Underscore provides functional concepts to JavaScript, and one of the key concepts of functional programming is Referential Transparency.

Essentially, functions do not have side-effects and will always return the same output for a given input. In other words, all functions are pure.

Removing an element from the array would indeed be a predictable result for the given input, but the result would be a side-effect rather than a return value. Thus, destructive functions do not fit into the functional paradigm.

Solution

The correct way to remove values from an array in Underscore has already been discussed at length on Stack Overflow here. As a side note, when using without, reject or filter, if you only want to remove a single instance of an item from an array, you will need to uniquely identify it. So, in this manner:

arr = _.without(arr, 5);

you will remove all instances of 5 from arr.

Community
  • 1
  • 1
Luke Willis
  • 8,429
  • 4
  • 46
  • 79