

Returns the last index of an element or -1 if the element doesn't exist. Returns the index of an element or -1 if the element doesn't exist. Runs a callback on every item of the array.

Tests if all the elements of an array pass a condition.Ĭreates a copy of the array with only the filtered items.Ĭreates a new array with all the sub-arrays flattened.Īpplies a callback to every item of an array and flattens the result. Here is a table with all the built-in array methods: NameĬopies part of an array to a location in the same array. Outputs: 2 console.log(animals.indexOf( 'dog')) Dictionary Sorting the array is done using the sort function. To find the index of an element, use the indexOf function. One of the most useful functions is the push method to add a new element to an array. The array prototype provides many built-in methods. Note: You can also initialize an array without writing its type. Here is an example: typescript const animals: Array = You can also initialize an empty array and add values later. Which of those methods you choose is a question of preference because they both produce the same result.

The second one uses the generic Array type. Here is an example: typescript const animals: string = In TypeScript, you have two different methods of initializing an array. Note: An array can also be readonly by using the readonly keyword or by using as const. Note: You can add multiple types of elements to an array by setting the array type to a union. Here we get an error because the array is of type number, but we are trying to add a string element. The TypeScript compiler will check the data type of the array's elements and prevent the developer from adding an element of an unallowed type. But we can also add it to make the code more verbose: typescript const ages: number = When we don't add a type to the array, TypeScript infers it. Here is a small example of an array of numbers: typescript const ages = You can use an array when you have a list of values and want to work with them as a collection.
