snippetjavascriptCritical
How do I check whether an array contains a string in TypeScript?
Viewed 0 times
arraytypescripthowcheckwhetherstringcontains
Problem
Currently I am using Angular 2.0. I have an array as follows:
How can I check in TypeScript whether the channelArray contains a string 'three'?
var channelArray: Array = ['one', 'two', 'three'];How can I check in TypeScript whether the channelArray contains a string 'three'?
Solution
The same as in JavaScript, using Array.prototype.indexOf():
Or using ECMAScript 2016 Array.prototype.includes():
Note that you could also use methods like showed by @Nitzan to find a string. 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
Reference
Array.find()
Array.some()
Array.filter()
console.log(channelArray.indexOf('three') > -1);Or using ECMAScript 2016 Array.prototype.includes():
console.log(channelArray.includes('three'));Note that you could also use methods like showed by @Nitzan to find a string. 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'}]Reference
Array.find()
Array.some()
Array.filter()
Code Snippets
console.log(channelArray.indexOf('three') > -1);console.log(channelArray.includes('three'));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'}]Context
Stack Overflow Q#42790602, score: 1016
Revisions (0)
No revisions yet.