【问题标题】:How do I Search an Array of Strings for specific Substring and Drop / Remove / Delete those Array Items that contain that Substring using Lodash?如何在字符串数组中搜索特定子字符串并使用 Lodash 删除/删除/删除包含该子字符串的数组项?
【发布时间】:2018-07-05 00:21:35
【问题描述】:

有大量与搜索/循环字符串数组和匹配给定子字符串相关的好问题/答案,但我无法轻易找到使用 Lodash 删除/删除任何数组元素的简洁示例确实包含所需的搜索子字符串

我找到的用于搜索/匹配字符串数组的最佳资源是这个问题(几个很好的答案):Use lodash to find substring from array of strings

这些答案似乎都不适用于立即删除与搜索/子字符串匹配(真)的项目。

有没有一种简单的方法可以循环遍历字符串数组并使用 Lodash 删除匹配的项目?

虽然还有其他选项,但我们最好使用 Lodash,因为我们已经依赖它来实现许多类似的功能。

【问题讨论】:

    标签: javascript arrays string search lodash


    【解决方案1】:

    所以我最终找到了一种使用 Lodash 的 _.remove 函数来完成此操作的方法,如下所示:

            // The String (SubString) we want to match against array (for dropping purposes)
            var searchSubString = "whatever" 
    
            // Remove all array items that contain the text "whatever"
            _.remove(my_array, function(searchSubString) {
                  return n.indexOf(searchSubString) !== -1;
                });
    

    基本上 indexOf 是匹配字符串中子字符串的位置,如果没有找到子字符串,它将返回 -1,当 indexOf 返回一个不是 -1 的数字时(该数字是子字符串在字符数中的位置Array 字符串)Lodash 通过 Array 突变删除该项目。

    参考资料: Lodash _.remove documentation

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2015-10-02
      相关资源
      最近更新 更多