Ricardo Borges

Ricardo Borges

Personal blog

Data Structures in TypeScript - Array

An array is a common data structure that holds items of the same type, in TypeScript, unlike other languages, an array doesn't have a fixed length. Also, in TypeScript, you don't have to re-organize all elements of an array when makings operations like insert or delete.

Representation

array

  • Elements are the items stored in an array
  • Index is the location of an element in an array, it goes from 0 to (array length - 1)
1/** An array can be written like this **/
2
3const numbers: number[] = [1, 2, 3, 4]
4const names = string[] = ['Snake', 'Ocelot', 'Otacon', 'Naomi']
5
6/** Also can be written using a generic array type, Array<elemType> **/
7
8let list: Array<number> = [1, 2, 3, 4]
9let list: Array<string> = ['Snake', 'Ocelot', 'Otacon', 'Naomi']

Basics operations

Traverse - Print all array items one by one

1/** 3 ways to iterate an array **/
2
3for(let i=0; i<array.length; i++) {
4    console.log(array[i])
5}
6
7for(const item of array) {
8    console.log(item)
9}
10
11array.forEach(item => {
12    console.log(item)
13})

Insertion - Add an item

1/** add to the end **/
2array.push(5)
3
4/** add to the beginning **/
5array.unshift(0)
6
7/** add in a specific index position **/
8array.splice(3, 0, 8) // add 8 in the index 3

Deletion - Remove an item

1/** remove from the end **/
2array.pop()
3
4/** remove from the beginning **/
5array.shift()
6
7/** remove from a specific index position **/
8array.splice(2, 1) // remove from index 2

Update - Update an item

1/** update element in position 1 **/
2array[1] = 7

Search - Search by an item

1/** you can traverse an array to find an element by its value, or simply use the .find() function **/
2
3const item = array.find(item => item === 3) // search by an item with value 3

Strings are arrays of characters

All above operations can be performed on strings to solve problems like count the occurrences of a character in a string:

1let str = "aabbccdd"
2let occurrences = 0
3
4for(let i=0; i < str.length; i++) {
5    if(str[i] === "c") {
6        occurrences++
7    }
8}
9
10console.log(occurrences) // prints 2
github iconlinkedin icontwitter icon
Buy Me A Coffee