- TypeScript — Arrays
- Features of an Array
- Declaring and Initializing Arrays
- Syntax
- Accessing Array Elements
- Example: Simple Array
- Example: Single statement declaration and initialization
- Array Object
- Example
- Example: Array Constructor accepts comma separated values
- Array Methods
- Array Destructuring
- Example
- Array Traversal using for…in loop
- Arrays in TypeScript
- How to generate Number Range Array in TypeScript
- Integer value Array Range
- Ascending order array
- Descending order array
- Floating value Array Range
- Handle Big/Small Number with Log Notation
- End
- Related articles
TypeScript — Arrays
TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type.
Features of an Array
Here is a list of the features of an array −
- An array declaration allocates sequential memory blocks.
- Arrays are static. This means that an array once initialized cannot be resized.
- Each memory block represents an array element.
- Array elements are identified by a unique integer called as the subscript / index of the element.
- Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array.
- Array initialization refers to populating the array elements.
- Array element values can be updated or modified but cannot be deleted.
Declaring and Initializing Arrays
To declare an initialize an array in Typescript use the following syntax −
Syntax
var array_name[:datatype]; //declaration array_name = [val1,val2,valn..] //initialization
An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the array’s first element during initialization.
For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an array as given below −
The array pointer refers to the first element by default.
Arrays may be declared and initialized in a single statement. The syntax for the same is −
var array_name[:data type] = [val1,val2…valn]
Note − The pair of [] is called the dimension of the array.
Accessing Array Elements
The array name followed by the subscript is used refer to an array element. Its syntax is as follows −
array_name[subscript] = value
Example: Simple Array
var alphas:string[]; alphas = ["1","2","3","4"] console.log(alphas[0]); console.log(alphas[1]);
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10 var alphas; alphas = ["1", "2", "3", "4"]; console.log(alphas[0]); console.log(alphas[1]);
The output of the above code is as follows −
Example: Single statement declaration and initialization
var nums:number[] = [1,2,3,3] console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); console.log(nums[3]);
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10 var nums = [1, 2, 3, 3]; console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); console.log(nums[3]);
Array Object
An array can also be created using the Array object. The Array constructor can be passed.
- A numeric value that represents the size of the array or
- A list of comma separated values.
The following example shows how to create an array using this method.
Example
var arr_names:number[] = new Array(4) for(var i = 0;i
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10 var arr_names = new Array(4); for (var i = 0; i
Example: Array Constructor accepts comma separated values
var names:string[] = new Array(«Mary»,»Tom»,»Jack»,»Jill») for(var i = 0;i
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10 var names = new Array(«Mary», «Tom», «Jack», «Jill»); for (var i = 0; i
Array Methods
A list of the methods of the Array object along with their description is given below.
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
Sorts the elements of an array.
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
Array Destructuring
Refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of an array.
Example
var arr:number[] = [12,13] var[x,y] = arr console.log(x) console.log(y)
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10 var arr = [12, 13]; var x = arr[0], y = arr[1]; console.log(x); console.log(y);
Array Traversal using for…in loop
One can use the for…in loop to traverse through an array.
var j:any; var nums:number[] = [1001,1002,1003,1004] for(j in nums)
The loop performs an index based array traversal.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10 var j; var nums = [1001, 1002, 1003, 1004]; for (j in nums)
The output of the above code is given below −
Arrays in TypeScript
TypeScript supports the following concepts in arrays −
TypeScript supports multidimensional arrays. The simplest form of the multidimensional array is the twodimensional array.
You can pass to the function a pointer to an array by specifying the array’s name without an index.
Allows a function to return an array
How to generate Number Range Array in TypeScript
JavaScript/TypeScript doesn’t offer a function to generate a range array. What we want to do is something like this.
Array.range(5, 10); // [5, 6, 7, 8, 9, 10] Array.range(2, 10, 2); // [2, 4, 6, 8, 10]
How can we write code for this?
I created a module called yutolity that provides the functions. Go to npm and add it to your dependencies if you don’t want to write code.
Utility functions. Latest version: 1.4.0, last published: a year ago. Start using yutolity in your project by running `npm i yutolity`. There is 1 other project.
Integer value Array Range
Ascending order array
If we want to generate an integer array like [1, 2, 3, 4] we can generate it with this one line.
const res = Array.from(Array(5).keys()).map(x => x + 1); console.log(res); // [1, 2, 3, 4, 5]
If we want to start the array from 5 we need to change x + 1 to x + 5 ;
const res = Array.from(Array(5).keys()).map(x => x + 5); console.log(res); // [1, 2, 3, 4, 5]
Let’s make it to a function.
const range = (start, end) => Array.from(Array(end - start + 1).keys()).map(x => x + start); console.log(range(3, 6)); // [3, 4, 5, 6] console.log(range(-2, 2)); // [-2, -1, 0, 1]
Descending order array
The code shown above doesn’t work if the end value is smaller than the start. Let’s improve it.
export function range(start: number, end: number): number[] < start = Math.floor(start); end = Math.floor(end); const diff = end - start; if (diff === 0) < return [start]; >const keys = Array(Math.abs(diff) + 1).keys(); return Array.from(keys).map(x => < const increment = end >start ? x : -x; return start + increment; >); >
The last 5 lines are the main logic. It looks more complicated but it’s not hard. It just decides if it increments or decrements.
Floating value Array Range
If we want to generate a floating value array we need to implement it in a different way. Following is the first code that I wrote.
export function rangeByStep(start: number, end: number, step: number): number[] < if (end === start || step === 0) < return [start]; >if (step < 0) < step = -step; >const stepNumOfDecimal = step.toString().split(".")[1]?.length || 0; const endNumOfDecimal = end.toString().split(".")[1]?.length || 0; const maxNumOfDecimal = Math.max(stepNumOfDecimal, endNumOfDecimal); const power = Math.pow(10, maxNumOfDecimal); const increment = end - start > 0 ? step : -step; const intEnd = Math.floor(end * power); const isFulFilled = end - start > 0 ? (current: number) => current > intEnd: (current: number) => current < intEnd const result = []; let current = start; while (true) < result.push(current); // to address floating value const intValue = Math.floor(current * power) + Math.floor(increment * power); current = intValue / power; if (isFulFilled(intValue)) < break; >> return result; >
It’s much more complicated than the one for the integer version because it’s not so simple to handle floating values. When repeating to add 0.1 to the existing variable its result is 0.200000001 for example. Therefore, I converted the floating values to integers and then started calculations to prevent this. Furthermore, Math.floor returns -31 if the argument is like -30.0000001. I needed to replace the function with Math.trunc .
I thought that I could remove the value comparison if I wrote it in the same way as the integer version. The second version is the following.
export function rangeByStep(start: number, end: number, step: number): number[] < if (end === start || step === 0) < return [start]; >if (step < 0) < step = -step; >const stepNumOfDecimal = step.toString().split(".")[1]?.length || 0; const endNumOfDecimal = end.toString().split(".")[1]?.length || 0; const maxNumOfDecimal = Math.max(stepNumOfDecimal, endNumOfDecimal); const power = Math.pow(10, maxNumOfDecimal); const diff = Math.abs(end - start); const count = Math.trunc(diff / step + 1); step = end - start > 0 ? step : -step; const intStart = Math.trunc(start * power); return Array.from(Array(count).keys()) .map(x => < const increment = Math.trunc(x * step * power); const value = intStart + increment; return Math.trunc(value) / power; >); >
The following code gets the length of the number after the decimal point.
const stepNumOfDecimal = step.toString().split(".")[1]?.length || 0; const endNumOfDecimal = end.toString().split(".")[1]?.length || 0; // 11 -> 0 // 11.123 -> 3 // 123.12345 -> 5
This function can do the same thing that I wrote at the top of this article.
Array.range(2, 10, 2); // [2, 4, 6, 8, 10] rangeByStep(2, 10, 2); // [2, 4, 6, 8, 10]
Handle Big/Small Number with Log Notation
However, it can’t cover some cases when the number is very big or small because those numbers can be converted to log notation.
console.log(0.000000001); // 1e-9
My function checks the length after the decimal point but it doesn’t work without the dot “.”. The logic needs to be updated. The improved code is the following.
export function indexesOf( text: string, searchStrings: string[], position?: number ): IndexOfResult | undefined < for (const searchString of searchStrings) < const index = text.indexOf(searchString, position); if (index !== -1) < return < index, foundString: searchString, >; > > > export function getPrecision(value: number): number < const str = value.toString(); const searchStrings = ["e-", "e+"]; const found = indexesOf(str, searchStrings); if (found) < return parseInt(str.substring(found.index + 2)); >return str.split(".")[1]?.length || 0; > getPrecision(11.223); // 3 getPrecision(11.0); // 0 getPrecision(1e-11); // 11 getPrecision(1e+21); // 21
Even if it receives a log notation value it can get the precision. If we replace it with the previous version rangeByStep function supports all most all cases. I’m sure this is probably too much. In most cases, such a big/small number isn’t used.
The final version is the following.
export function rangeByStep(start: number, end: number, step: number): number[] < if (end === start || step === 0) < return [start]; >if (step < 0) < step = -step; >const stepPrecision = getPrecision(step); const endPrecision = getPrecision(end); const maxPrecision = Math.max(stepPrecision, endPrecision); const power = Math.pow(10, maxPrecision); const intStart = Math.round(start * power); const intEnd = Math.round(end * power); const diff = Math.abs(intEnd - intStart); const count = Math.trunc(diff / Math.round(step * power) + 1); step = end - start > 0 ? step : -step; return Array.from(Array(count).keys()) .map(x => < const increment = Math.round(x * step * power); const value = intStart + increment; return value / power; >); > rangeByStep(1, 7, 2); // [1, 3, 5, 7] rangeByStep(0.1, 0.3, -0.1); // [0.1, 0.2, 0.3] rangeByStep(0.3, -0.11, 0.1); // [0.3, 0.2, 0.1, 0, -0.1] rangeByStep(-0.2, 0.3, 1); // [-0.2] rangeByStep(0.000001, 0.000003, 0.000001); // [0.000001, 0.000002, 0.000003]
End
The logic to generate an integer range array is easy but not for a floating value. We need to consider calculation errors and log notation. It was a cumbersome calculation. I guess we use a normal integer range array in most cases so you can easily write the code yourself. Copy my code and paste it.
If you want to use the utility functions shown in this article you can add my module yutolity.
Related articles
Remove method doesn’t exist on Array interface. So we need to implement it ourselves. This article explains how to remove elements from number/string/object array.