Created
August 12, 2016 05:02
-
-
Save amowu/b64ad752201e355e15fa45432a3ffe66 to your computer and use it in GitHub Desktop.
Find a Substring in a JavaScript Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // The bitwise NOT (~) operator inverts the -1 to 0, and the !! operator coerces that value to false when the string is not in the array. | |
| var arr = ['foo', 'bar']; | |
| var str = 'baz'; | |
| var isTrue = !!~arr.indexOf(str); // return false | |
| str = 'foo'; | |
| isTrue = !!~arr.indexOf(str); // return true | |
| // Which is essentially a one-liner for this: | |
| var isTrue = true; | |
| if (arr.indexOf(str) === -1) { | |
| isTrue = false; | |
| } | |
| // Or, you can use ES2015’s Array.protoype.find() (with a Polyfill if required). | |
| var arr = ['foo', 'bar']; | |
| var str = 'food.land'; | |
| var isTrue = !!arr.find(function (elem) { | |
| return !!~str.indexOf(elem); // return true | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment