【问题标题】:How to filter a large array of strings by an array of substrings?如何通过子字符串数组过滤大量字符串?
【发布时间】:2019-05-02 21:17:53
【问题描述】:

我正在使用 angular 来过滤自动完成字段的大量字符串。 最有效的方法是什么?

largeArrayOfStrings = ['string1', 'string2', 'test one', 'one', 'two test', 'three', 'test one two', ...]
substring = [‘test’, ‘one’, ‘two’]

values = substringArray.map(h.includes)
// I would want values to be the following
values = ['test one two']
// That is the only string that contains all the strings from substring array.

【问题讨论】:

    标签: javascript arrays string dictionary filter


    【解决方案1】:

    好的,所以我一直在编写一个库来做这样的事情,我找到了一个非常简单的解决方案来解决这个问题。代码原本是用 TypeScript 写的,但我已经转成 JS:

    const filterArray = (arr, toKeep) => {
        for (item of toKeep)
            arr = arr.filter(i => i = toKeep);
    
        return arr;
    };
    

    这就是说这个函数假设数组中可以有字符串以外的项目,如果你想确保字符串,只需在函数开头添加这一行:

    for (arrIetm of arr) if (Object.prototype.toString.call(arrItem) != '[object String]' return;
    

    顺便说一句,如果你想查看这个库,GitHub 在这个链接: https://railrunner16.me/raildash/

    祝你好运!

    【讨论】:

      【解决方案2】:

      这是一种方法:

      const strings = ['string1', 'string2', 'test one', 'one', 'two test', 'three', 'test one two']
      const subs = ['test', 'one', 'two']
      
      const result = strings.filter(x => subs.every(y => x.includes(y)))
      
      console.log(result)

      Array.filterArray.everyString.includes 结合使用。

      我们的想法是从单词过滤器开始,并确保 every 数组中的 subs 子字符串在主数组的当前单词中得到命中。这只发生在'test one two' 上,如图所示。

      【讨论】:

        【解决方案3】:

        h变成一个Set,它有固定的查找时间:

          const toFilter = new Set(h);
        
          const result = substringArray.filter(el => toFilter.has(el));
        

        【讨论】:

          猜你喜欢
          • 2022-01-13
          • 2022-07-04
          • 2021-06-06
          • 2010-11-20
          • 2016-01-11
          • 2021-12-15
          • 2018-09-28
          • 2017-07-15
          • 2022-12-05
          相关资源
          最近更新 更多