使用lodash从字符串数组中查找子字符串 [英] use lodash to find substring from array of strings

查看:1364
本文介绍了使用lodash从字符串数组中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习lodash。是否可以使用lodash在字符串数组中查找子字符串?

I'm learning lodash. Is it possible to use lodash to find a substring in an array of strings?

    var myArray = [
    'I like oranges and apples',
    'I hate banana and grapes',
    'I find mango ok',
    'another array item about fruit'
    ]

是否可以确认oranges这个词是否在我的数组中?
我试过_.includes,_.some,_.indexOf但是他们都看错了,因为他们查看完整的字符串,而不是子字符串

is it possible to confirm if the word 'oranges' is in my array? I've tried _.includes, _.some, _.indexOf but they all failed as they look at the full string, not a substring

推荐答案

您可以使用lodash的更高版本轻松地为 some()构建一个iteratee订单功能。例如:

You can easily construct an iteratee for some() using lodash's higher-order functions. For example:

_.some(myArray, _.unary(_.partialRight(_.includes, 'orange')));

unary()函数确保只有一个参数传递给回调。 partialRight()函数用于应用'orange' value作为 includes()的第二个参数。第一个参数是每次迭代 some()提供的。

The unary() function ensures that only one argument is passed to the callback. The partialRight() function is used to apply the 'orange' value as the second argument to includes(). The first argument is supplied with each iteration of some().

但是,这种方法不起作用区分大小写很重要例如,'Orange'将返回false。以下是处理区分大小写的方法:

However, this approach won't work if case sensitivity matters. For example, 'Orange' will return false. Here's how you can handle case sensitivity:

_.some(myArray, _.method('match', /Orange/i));

method()函数创建一个函数,该函数将调用传递给它的第一个参数的给定方法。在这里,我们匹配不区分大小写的正则表达式。

The method() function creates a function that will call the given method of the first argument passed to it. Here, we're matching against a case-insensitive regular expression.

或者,如果区分大小写并不重要,您只需要方法()方法,这也适用于ES2015:

Or, if case-sensitivity doesn't matter and you simply prefer the method() approach, this works as well for ES2015:

_.some(myArray, _.method('includes', 'orange'));

这篇关于使用lodash从字符串数组中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆