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 hat
You can do this using lodash, but it's also very doable using native javascript methods:
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 contains in our case) must return true or false. While iterating through the array elements, if any of the elements returns true, the some method returns 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.
Cheers!