How do I check whether an array contains a string in TypeScript?

var array: Array<string> = ['one', 'two', 'abc'];

The same as in JavaScript, using Array.prototype.indexOf():

console.log(array.indexOf('abc') > -1);

Or using ECMAScript 2016 Array.prototype.includes():

console.log(array.includes('abc'));

However, you wouldn’t usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]

References:

Array.find()

Array.some()

Array.filter()

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store