Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'?

like image 926
code1 Avatar asked Mar 14 '17 15:03

code1


People also ask

How do you check if an array contains a string in TypeScript?

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!

How do you check if an array includes a string?

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.

How do I check if a variable contains a string in TypeScript?

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 ...


2 Answers

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()

like image 186
baao Avatar answered Sep 18 '22 02:09

baao


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 
like image 44
Nitzan Tomer Avatar answered Sep 18 '22 02:09

Nitzan Tomer