[javascript] 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'?

This question is related to javascript arrays typescript

The answer is


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

TS has many utility methods for arrays which are available via the prototype of Arrays. There are multiple which can achieve this goal but the two most convenient for this purpose are:

  1. Array.indexOf() Takes any value as an argument and then returns the first index at which a given element can be found in the array, or -1 if it is not present.
  2. Array.includes() Takes any value as an argument and then determines whether an array includes a this value. The method returning true if the value is found, otherwise false.

Example:

const channelArray: string[] = ['one', 'two', 'three'];

console.log(channelArray.indexOf('three'));      // 2
console.log(channelArray.indexOf('three') > -1); // true
console.log(channelArray.indexOf('four') > -1);  // false
console.log(channelArray.includes('three'));     // true

do like this:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }

Also note that "in" keyword does not work on arrays. It works on objects only.

propName in myObject

Array inclusion test is

myArray.includes('three');

If your code is ES7 based (or upper versions):

channelArray.includes('three'); //will return true or false

If not, for example you are using IE with no babel transpile:

channelArray.indexOf('three') !== -1; //will return true or false

the indexOf method will return the position the element has into the array, because of that we use !== different from -1 if the needle is found at the first position.


You can use filter too

this.products = array_products.filter((x) => x.Name.includes("ABC"))

Use JavaScript Array includes() Method

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");

Try it Yourself » link

Definition

The includes() method determines whether an array contains a specified element.

This method returns true if the array contains the element, and false if not.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?