Lodash 从字符串数组中删除
Lodash remove from string array
我有一个字符串数组,想立即删除其中的一些。但是不行
var list = ['a', 'b', 'c', 'd']
_.remove(list, 'b');
console.log(list); // 'b' still there
我猜这是因为 _.remove
函数接受字符串作为第二个参数并认为这是 属性 名称。在这种情况下,如何让 lodash 进行相等性检查?
函数 _.remove 不接受字符串作为第二个参数,而是接受为数组中的每个值调用的谓词函数。如果函数 returns true
从数组中删除该值。
Lodas 文档:https://lodash.com/docs#remove
Removes all elements from array that predicate returns truthy for and
returns an array of the removed elements. The predicate is bound to
thisArg and invoked with three arguments: (value, index, array).
所以,如果你想从数组中删除 b
,你应该像这样:
var list = ['a', 'b', 'c', 'd']
_.remove(list, function(v) { return v === 'b'; });
["a", "c", "d"]
正如 Giuseppe Pes 指出的那样,_.remove
需要一个函数。一种更直接的方法是使用 _.without
, 直接删除元素。
_.without(['a','b','c','d'], 'b'); //['a','c','d']
您还有一个选择是使用 _.pull,它与 _.without 不同,它不会创建数组的副本,而只会修改它:
_.pull(list, 'b'); // ['a', 'c', 'd']
我有一个字符串数组,想立即删除其中的一些。但是不行
var list = ['a', 'b', 'c', 'd']
_.remove(list, 'b');
console.log(list); // 'b' still there
我猜这是因为 _.remove
函数接受字符串作为第二个参数并认为这是 属性 名称。在这种情况下,如何让 lodash 进行相等性检查?
函数 _.remove 不接受字符串作为第二个参数,而是接受为数组中的每个值调用的谓词函数。如果函数 returns true
从数组中删除该值。
Lodas 文档:https://lodash.com/docs#remove
Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array).
所以,如果你想从数组中删除 b
,你应该像这样:
var list = ['a', 'b', 'c', 'd']
_.remove(list, function(v) { return v === 'b'; });
["a", "c", "d"]
正如 Giuseppe Pes 指出的那样,_.remove
需要一个函数。一种更直接的方法是使用 _.without
, 直接删除元素。
_.without(['a','b','c','d'], 'b'); //['a','c','d']
您还有一个选择是使用 _.pull,它与 _.without 不同,它不会创建数组的副本,而只会修改它:
_.pull(list, 'b'); // ['a', 'c', 'd']