【问题标题】:Ramda, check(filter) if array of strings contains substringRamda,检查(过滤)字符串数组是否包含子字符串
【发布时间】:2019-02-04 03:35:35
【问题描述】:

例如我有一个数组:

let data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ]

和测试子串:

const searchStr = 'abc'

我需要另一个数组,其中包含来自data 数组的任何匹配值。

let result = ['abc', 'dfgxabc']

在我的任务中,我从键盘输入中获取一个字符串,它可以包含至少 3 个字符或更多字符。所以它类似于实时搜索。

我正在尝试使用 Ramda:

const data = [ 'abc', 'dfg', 'xyz' ]

const searchStr = 'abc'

const filtered = R.filter(R.match(new RegExp(searchStr, 'i')), data)

【问题讨论】:

    标签: javascript arrays string filter substring


    【解决方案1】:

    你可以在 Array.prototype.filterRegExp.prototype.test 的帮助下使用原生 js 来实现

    const data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ];
    
    const searchStr = 'abc';
    
    const filtered = data.filter(s => new RegExp(searchStr, 'ig').test(s));
    
    console.log(filtered);

    【讨论】:

      【解决方案2】:

      为了直接回答问题,

      const data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ];
      
      const findABC = filter(test(/abc/));
      
      findABC(data)
      

      相当于使用 Ramda。看看REPL

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 2011-11-09
        • 2013-05-18
        • 1970-01-01
        • 2021-12-20
        • 2020-11-28
        • 2014-11-22
        • 2013-02-05
        • 1970-01-01
        相关资源
        最近更新 更多