Javascript 使用 lodash 从字符串数组中查找子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35615413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use lodash to find substring from array of strings
提问by John Paul Vaughan
I'm learning lodash. Is it possible to use lodash to find a substring in an array of strings?
我正在学习 lodash。是否可以使用 lodash 在字符串数组中查找子字符串?
var myArray = [
'I like oranges and apples',
'I hate banana and grapes',
'I find mango ok',
'another array item about fruit'
]
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
是否可以确认“oranges”这个词是否在我的数组中?我试过 _.includes, _.some, _.indexOf 但当他们查看完整字符串而不是子字符串时,它们都失败了
回答by Adam Boduch
You can easily construct an iteratee for some()using lodash's higher-order functions. For example:
您可以使用 lodash 的高阶函数轻松地为some()构造迭代对象。例如:
_.some(myArray, _.unary(_.partialRight(_.includes, 'orange')));
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()
.
的一元() ,只有一个参数被传递给回调函数可以确保。所述partialRight()函数是用于施加'orange'
值作为第二个参数包括() 。第一个参数随 的每次迭代提供some()
。
However, this approach won't work if case sensitivity matters. For example, 'Orange'
will return false. Here's how you can handle case sensitivity:
但是,如果区分大小写很重要,这种方法将不起作用。例如,'Orange'
将返回false。以下是处理区分大小写的方法:
_.some(myArray, _.method('match', /Orange/i));
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.
该方法()函数创建,将调用传递给它的第一个参数的给定方法的功能。在这里,我们匹配不区分大小写的正则表达式。
Or, if case-sensitivity doesn't matter and you simply prefer the method()
approach, this works as well for ES2015:
或者,如果区分大小写无关紧要,而您只是更喜欢这种method()
方法,那么这也适用于 ES2015:
_.some(myArray, _.method('includes', 'orange'));
回答by James
Two quick ways to do it - neither uses lodash (sorry)
两种快速的方法 - 都不使用 lodash(抱歉)
var found = myArray.filter(function(el){
return el.indexOf('oranges') > -1;
}).length;
if (found) { // oranges was found }
or as I mentioned in the comment:
或者正如我在评论中提到的:
var found = myArray.join(',').indexOf('oranges') > -1;
if (found) { // oranges was found }
回答by Isaiah Lee
You can do this using lodash, but it's also very doable using native javascript methods:
您可以使用 lodash 来做到这一点,但使用原生 javascript 方法也非常可行:
function stringArrayContains(array, str) {
function contains(el) {
return (el.indexOf(str) !== -1) ? true : false;
}
return array.some(contains);
}
Testing the above function:
测试上述功能:
var a = ['hello', 'there'];
var b = ['see', 'ya', 'later'];
stringArrayContains(a, 'ell') // true
stringArrayContains(a, 'what') // false
stringArrayContains(b, 'later') // true
stringArrayContains(b, 'hello') // false
Array.prototype.some applies a function you define to every element of an array. This function (named containsin our case) must return true or false. While iterating through the array elements, if any of the elements returns true, the somemethod returns true.
Array.prototype.some 将您定义的函数应用于数组的每个元素。这个函数(在我们的例子中命名为contains)必须返回 true 或 false。在迭代数组元素时,如果任何元素返回true,则some方法返回 true 。
Personally, I think in general that if you can use native JS methods for simple functions, it's preferable to loading an library just to do the same thing. Lodash absolutely does have performance benefits, but they aren't necessarily realized unless you're processing large amounts of data. Just my two cents.
就我个人而言,我认为总的来说,如果您可以使用原生 JS 方法来实现简单的功能,那么最好加载一个库来做同样的事情。Lodash 确实具有性能优势,但除非您正在处理大量数据,否则不一定会实现它们。只有我的两分钱。
Cheers!
干杯!
回答by Alex Yatkevich
The best way is to define a function to check the inclusion of a substring.
最好的方法是定义一个函数来检查是否包含子字符串。
var contains = _.curry(function (substring, source) {
return source.indexOf(substring) !== -1;
});
I use _.curry
here to get a curried function, which can be partially applied then.
我_.curry
在这里使用得到一个柯里化函数,然后可以部分应用。
_.some(myArray, contains('item'));
You can also find a substring in a joined string.
您还可以在连接的字符串中查找子字符串。
contains('item', _.join(myArray))
UPD:
更新:
I have not noticed that lodash already has a function to find value in a collection.
我没有注意到 lodash 已经有一个在集合中查找值的函数。
The function _.includes
is quite the same to what I defined above. However, as everything in lodash, it uses the different order for arguments. In my example, I put a source as the latest argument for a curried function which makes my function useful for point-free style programming when lodash waits for the source as a first argument of the same function.
该函数_.includes
与我上面定义的完全相同。但是,与 lodash 中的所有内容一样,它使用不同的参数顺序。在我的示例中,我将源代码作为柯里化函数的最新参数,这使得我的函数在 lodash 等待源代码作为同一函数的第一个参数时可用于无点风格编程。
Check the Brian Lonsdorf's talk on this matter https://www.youtube.com/watch?v=m3svKOdZijA
查看 Brian Lonsdorf 关于此事的演讲https://www.youtube.com/watch?v=m3svKOdZijA
Also take a chance to look into ramda. This library provides a better way for practical functional programming in JavaScript.
回答by Necevil
I ran into this Question / Answer thread while trying to figure out how to match a substring against each String in an Array and REMOVE any array item that contains that substring.
我在尝试找出如何将子字符串与数组中的每个字符串匹配并删除包含该子字符串的任何数组项时遇到了这个问题/答案线程。
While the above answers put me on track, and while this doesn't specifically answer the original question, this thread DOES appear first in the google search when you are trying to figure out how to accomplish the above removal of an array item so I figured I would post an answer here.
虽然上面的答案让我走上了正轨,虽然这并没有具体回答原始问题,但当您试图弄清楚如何完成上述删除数组项的操作时,该线程确实首先出现在谷歌搜索中,所以我想我会在这里发布答案。
I ended up finding a way to use Lodash's _.remove function to remove matching array strings as follows:
我最终找到了一种使用 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;
});
Basically indexOf is matching against the position of the substring within the string, if the substring is not found it will return -1, when indexOf returns a number other than -1 (the number is the SubString position in number of characters within the Array string).
基本上 indexOf 是匹配子字符串在字符串中的位置,如果没有找到子字符串,它将返回 -1,当 indexOf 返回 -1 以外的数字时(该数字是 Array 字符串中字符数中的 SubString 位置) )。
Lodash removes that Array item via array mutation and the newly modified array can be accessed by the same name.
Lodash 通过数组变异删除该数组项,新修改的数组可以通过相同的名称访问。
回答by Brice
let str1 = 'la rivière et le lapin sont dans le près';
let str2 = 'product of cooking class';
let str3 = 'another sentence to /^[analyse]/i with weird!$" chars@';
_.some(_.map(['rabbit','champs'], w => str1.includes(w)), Boolean), // false
_.some(_.map(['cook'], w => str2.includes(w)), Boolean), // true
_.some(_.map(['analyse'], w => str3.includes(w)), Boolean), // true
回答by stasovlas
_.some(myArray, function(str){
return _.includes(str, 'orange')
})