首页 > 解决方案 > 如何在 Lodash 中将 _.pull() 与正则表达式一起使用?

问题描述

我想在匹配某个正则表达式时从数组中删除元素。

这是有关该pull()方法的 Lodash 文档。

我想要一个类似的结果。

const array = ['a', 'b', 'c', 'a', 'b', 'c'];
 
_.pull(array, 'b', 'c',);
console.log(array); // [ 'a', 'a', ]

只是,我想使用正则表达式而不是字符串。但这并没有达到那个结果。

const array = ['a', 'b', 'c', 'a', 'b', 'c'];
const re = /(b|c)/gm
 
_.pull(array, re,);
console.log(array); // ["a", "b", "c", "a", "b", "c"]

我究竟做错了什么?

标签: javascriptarrayslodash

解决方案


_.pull()方法不接受谓词,请使用_.remove()

从数组中删除谓词返回真值的所有元素

const array = ['a', 'b', 'c', 'a', 'b', 'c'];
const re = /b|c/
 
_.remove(array, c => re.test(c));

console.log(array); // ["a", "a"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


推荐阅读