Skip to content

Instantly share code, notes, and snippets.

@amowu
Created August 12, 2016 05:02
Show Gist options
  • Select an option

  • Save amowu/b64ad752201e355e15fa45432a3ffe66 to your computer and use it in GitHub Desktop.

Select an option

Save amowu/b64ad752201e355e15fa45432a3ffe66 to your computer and use it in GitHub Desktop.
Find a Substring in a JavaScript Array
// 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