Remove value from array in Underscore

隐身守侯 提交于 2019-12-10 17:22:32

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/18363083/remove-value-from-array-in-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!