Currently I am using Angular 2.0. I have an array as follows:
var channelArray: Array<string> = ['one', 'two', 'three'];
How can I check in TypeScript whether the channelArray contains a string 'three'?
Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise. Copied!
To check if a string is contained in an array, call the indexOf method, passing it the string as a parameter. The indexOf method returns the index of the first occurrence of the string in the array, or -1 if the string is not contained in the array.
In typescript, string contains is one of the features and also it is referred to and implemented using the includes() method which is used to determine the string characters whether it contains the characters of the specified string or not by using this method we can return the boolean values like true and false ...
The same as in JavaScript, using Array.prototype.indexOf():
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()
You can use the some method:
console.log(channelArray.some(x => x === "three")); // true
You can use the find method:
console.log(channelArray.find(x => x === "three")); // three
Or you can use the indexOf method:
console.log(channelArray.indexOf("three")); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With