Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove value from array in Underscore

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

like image 956
savinger Avatar asked Dec 12 '22 12:12

savinger


1 Answers

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.

like image 114
Luke Willis Avatar answered Dec 31 '22 08:12

Luke Willis