Lodash从字符串数组中删除

jus*_*ris 10 javascript lodash

我有一个字符串数组,想要立即删除其中的一些.但它不起作用

var list = ['a', 'b', 'c', 'd']
_.remove(list, 'b');
console.log(list); // 'b' still there
Run Code Online (Sandbox Code Playgroud)

我想这是因为_.remove函数接受字符串作为第二个参数,并认为这是属性名称.在这种情况下如何让lodash进行相等检查?

tre*_*vor 23

另一个选择是使用_.pull,与_.without不同,它不会创建数组的副本,而只是修改它:

_.pull(list, 'b'); // ['a', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

参考:https://lodash.com/docs#pull


Ret*_*sam 5

正如 Giuseppe Pes 指出的那样,_.remove期待一个功能。做你想做的更直接的方法是使用_.without,它确实需要直接删除元素。

_.without(['a','b','c','d'], 'b');  //['a','c','d']
Run Code Online (Sandbox Code Playgroud)