Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
32 views
7 pages
100 Days of TypeScript (Day 7)
Uploaded by
Leonardo Forero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save 100 Days of TypeScript (Day 7) For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
32 views
7 pages
100 Days of TypeScript (Day 7)
Uploaded by
Leonardo Forero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save 100 Days of TypeScript (Day 7) For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 7
Search
Fullscreen
100 Days of TypeScript (Day 7) How to use arrays to manage multiple items In this post, we look into using arrays to manage multiple items. First of all, 'd like to apologise for the delay in getting around to this post. There’s been a lot going on that's got in the way but | haven't forgotten about writing this series. On day 6, we learned how to use inheritance and abstract classes to show how we model “objects”. In this post, we are going to start looking into using arrays to manage multiple items. What Is an Array? We can think of an array as a handy way to create a collection of “things” that we can easily work with. Going back to my musical instrument example, we could think of the strings on a guitar as being an array of “strings” (musical strings here, rather than text strings), On a guitar, each string is a particular width depending on how high the tuning of that string is meant to be. Now, if we wanted to refer to these in our code, we could choose to create individual variables, e.g., string1, string2, and so on. This becomes very cumbersome to use and limits us when we have 7 string, 8 string, or even 12 string guitars. With an array, we simply need a single array that we just add the individual strings into. Declaring Arrays There are a number of different ways in which we can create arrays. If we know the contents of our array upfront, an easy way of creating and populating our array is this: TypeScript const strings: number[] = [1, 13, 17, 26, 36, 46];Ihave specified the type here, but this is not strictly necessary. We could leave out the number[] part and this would still create an array of numbers like the following: TypeScript const strings = [18, 13, 17, 26, 36, 46]; TypeScript is clever enough to know that this is an array of numbers so it won't allow us to add a different type to this array. Now, | did mention that there are other ways to declare an array. TypeScript also provides us with the ability to use something called a generic type to create an array. Don't worry what a generic is for the moment, we will be covering generics in a lot more detail later on in this series. Anyway, an alternative way to declare the same populated array looks like this: TypeScript const genericString: Array
= [1@, 13, 17, 26, 36, 46]3 The Arraycnumber> is the generic type for the array and is, functionally, identical to the original array declaration above. Declaring Empty Arrays We don't always know what we want to put into our array. There are lots of situations where we want to add items into our array after we have declared them. If we are using the [] syntax for our array, then we would declare our array like this. TypeScript const enptyStrings: nunber[] = []; If we want to use the Array<> syntax, we have two choices available to us. The first choice is to use: TypeScript const emptyGenericStrings: Array
= []; Alternatively, as this is a type, we can use the new() syntax like this: TypeScript const emptyGenericStrings2: Array
= new Array
(); Adding Elements to Our ArrayObviously, when we create an empty array (or even a pre-populated one in most cases), we want to be able to add entries into it whenever we need. No matter which way we created the array, whether using the Array<> syntax or as a [] type, we use exactly the same method to add an element into it. The keyword that we use is push and it looks like this: TypeScript enptyGenericStrings..push(3); If we want to add more than one element at a time, we can do so with the same command: TypeScript enptyGenericStrings .push(42, 52,60) ; Whether we choose to add an entry at a time, or as multiple elements in one go, these elements are added at the end of our list. This means that after our first entry, our list array looks like this: Array 20 Array with our first entry added Now, if we add push another entry into our array, it would look like this: Array —ame] | S J Array with two entries Removing Array Entries Over time, items become stale or unnecessary so we no longer need to keep them in our array. If we wanted to remove the very last entry, we use the pop command. Suppose we started with this array:Array with 4 elements When the pop command is used, we are left with the first three elements like this: Array 60 pop) | Array with 3 elements left after pop Having seen some lovely diagrams showing what the pop operation does, how would we actually use it? It’s as simple as the following TypeScript const popString = [ 3@, 40, 58, 6@ Jj popString.pop(); Well, that's simple enough, but how do we remove a single item from elsewhere in the list? This is slightly more compicated. What we need to do is find the index of the record that we want to remove using the indexoF function and then use the splice function to remove this element. In this example, we are creating an array of strings and then we are going to remove the item2 entry. TypeScript i const sliceStrings = "item3 const index = sliceStrings.indexof("item2"); sliceStrings.splice(index, 1);The second parameter in the splice call tells the code how many items to remove. If we wanted to remove iten2 and iten3, we could use splice(index, 2) to achieve this. Note: The splice function returns the items you have removed from the array. Suppose we wanted to remove multiple entries from an array. How would we go about doing this? There are multiple ways to achieve this. For these examples, we are going to spice things up a bit and show that arrays work with more than basic types. Let's create a guitar type that we can add to an array. The type consists of a model name, and the number of strings the guitar has. TypeScript interface Guitar { model: string, strings: number ? let guitars: Guitar[] = [15 We are going to create a helper method to simplify adding entries into our array and then add some entries. TypeScript function guitar(model: string, strings: number = 6): Guitar { return { model: model, strings: strings}; } guitars.push(guitar('Fender Stratocaster’); guitars. push(guitar( ‘Gibson Les Paul Anniversary')); guitars.push(guitar('Fender Villager’, 12)); guitars.push(guitar( ‘Dreadnought 12 String Acoustic’, 12)); What | want to do now is remove any guitar that doesn’t have six strings. The first method we could use is to filter the array so that it gives us only the entries we want. We have to copy the filtered version back onto the original array so that it overwrites it. TypeScript guitars = guitars.filter((gte) => gtr.strings === 6)5 Now, while we could do this, it's not one that | really recommend. The alternate method is to iterate (loop) over the array and remove the relevant entries. To do this, we have to start at the last entry and work our way back to the first entry, splicing the ones we want to remove. If we start at the beginning of our array, we run the risk of missing entries that sit next to each other. TypeScript for (let i = guitars.length -1; i >= @; if (guitars[i].strings !== 6) { guitars.splice(i, 1);It may look a little bit weird that we start at the length -1. Instinctively, we would think that we would start at the length but, for historical reasons, arrays actually start at position @ rather than 1. This means that we have an offset here that we have to take into account, which is why this is -1. Inserting Items Into an Array The last common array operation | want to touch on in this post is how to insert a ata set position, rather than adding it to the end. The ability to do this is straightforward. We are going to use the splice function, this time telling it to remove 0 elements. This function is very versatile because it gives us an extra parameter to specify the element we want to add. If | want to insert another guitar in the second position in the list, | simply do the following: m into an array TypeScript guitars.splice(1, @, guitar('Ibanez Jem 777'))3 Conclusion So, there we have it. We have covered most of the basics about working with arrays in TypeScript. We know how to create both empty and populated arrays, as well as how to add and remove items from the array. In the next post, we are going to move away from working purely in the console and start working with TypeScript as a companion to web applications As always, the accompanying code is available on Github. License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Written By Pete O'Hanlon CEO &B United Kingdom A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. | live in the North East of England with 2 wonderful daughters and a wonderful wife.lam not the Stig, but | do wish I had Lotus Tuned Suspension. v Comments and Discussions 231 message has been posted for this article Visit https://www.codeproject.com/Articles/5355433/100-Days-of-TypeScript-Day-11 to post and view comments on this article, or click here to get a print view with messages. Permalink Article Copyright 2023 by Pete O'Hanlon Advertise Everything else Copyright © CodeProject, Privacy 1999-2023 Cookies Terms of Use Web03 2.8:2023-01-23:1
You might also like
BookCars - Car Rental Platform With Mobile App
PDF
No ratings yet
BookCars - Car Rental Platform With Mobile App
48 pages
UNIT-II Array, Functions and String
PDF
No ratings yet
UNIT-II Array, Functions and String
34 pages
5 Array Method
PDF
No ratings yet
5 Array Method
101 pages
Javascriptarrays 141202114627 Conversion Gate01
PDF
No ratings yet
Javascriptarrays 141202114627 Conversion Gate01
17 pages
GIAIC - 04-Arrays and Strings
PDF
No ratings yet
GIAIC - 04-Arrays and Strings
22 pages
5 HSH
PDF
No ratings yet
5 HSH
5 pages
Type Script
PDF
No ratings yet
Type Script
52 pages
174 WDB Arrays
PDF
No ratings yet
174 WDB Arrays
15 pages
Compare Two Excel Files
PDF
No ratings yet
Compare Two Excel Files
9 pages
Angular Typescript
PDF
No ratings yet
Angular Typescript
36 pages
Array
PDF
No ratings yet
Array
8 pages
JS Array Metods
PDF
No ratings yet
JS Array Metods
31 pages
JS - Arrays in JS
PDF
No ratings yet
JS - Arrays in JS
3 pages
CSS Unit2 Notes
PDF
No ratings yet
CSS Unit2 Notes
77 pages
Javascript Objects
PDF
No ratings yet
Javascript Objects
37 pages
07 Arrays
PDF
No ratings yet
07 Arrays
23 pages
CSS Chapter 2
PDF
No ratings yet
CSS Chapter 2
99 pages
Section 27 - A Closer Look at Generics
PDF
No ratings yet
Section 27 - A Closer Look at Generics
2 pages
Angular Important
PDF
No ratings yet
Angular Important
28 pages
Array in Typescript
PDF
No ratings yet
Array in Typescript
3 pages
Unit 2 - Array - Function - String
PDF
No ratings yet
Unit 2 - Array - Function - String
42 pages
Untitled
PDF
No ratings yet
Untitled
19 pages
JS - 4
PDF
No ratings yet
JS - 4
5 pages
CSS CH-2 Updated
PDF
No ratings yet
CSS CH-2 Updated
30 pages
Array Functions in Typescript
PDF
No ratings yet
Array Functions in Typescript
2 pages
Arrays in Java Script
PDF
No ratings yet
Arrays in Java Script
15 pages
TypeScript - Crash Course. Concise and Clear TypeScript Tutorial - by Jan Cibulka - Medium
PDF
No ratings yet
TypeScript - Crash Course. Concise and Clear TypeScript Tutorial - by Jan Cibulka - Medium
11 pages
HTML5 Event Calendar - Scheduler
PDF
No ratings yet
HTML5 Event Calendar - Scheduler
30 pages
New Ichapter 2 CSS
PDF
No ratings yet
New Ichapter 2 CSS
6 pages
Arrays in JavaScript
PDF
No ratings yet
Arrays in JavaScript
11 pages
The Arrays Object
PDF
No ratings yet
The Arrays Object
7 pages
Secure FTP or SFTP Using Putty-PSFTP With C# (Open Source) and Task Scheduler Configuration
PDF
No ratings yet
Secure FTP or SFTP Using Putty-PSFTP With C# (Open Source) and Task Scheduler Configuration
9 pages
Alternative Analog SVG Clock
PDF
No ratings yet
Alternative Analog SVG Clock
8 pages
Array Methods Summary
PDF
No ratings yet
Array Methods Summary
74 pages
Array in JavaScript
PDF
No ratings yet
Array in JavaScript
11 pages
Unit 3 TypeScript
PDF
No ratings yet
Unit 3 TypeScript
42 pages
Js 2
PDF
No ratings yet
Js 2
3 pages
Writing Custom Control With New WPF XAML Designer
PDF
No ratings yet
Writing Custom Control With New WPF XAML Designer
6 pages
Ajp Practical 3
PDF
No ratings yet
Ajp Practical 3
5 pages
1-9 Arrays - Learn Web Development - MDN
PDF
No ratings yet
1-9 Arrays - Learn Web Development - MDN
13 pages
Client Side Scripting Chapter 2
PDF
No ratings yet
Client Side Scripting Chapter 2
14 pages
JS Array
PDF
No ratings yet
JS Array
5 pages
CSS Unit 2
PDF
No ratings yet
CSS Unit 2
13 pages
Lecture JS Arrays
PDF
No ratings yet
Lecture JS Arrays
34 pages
Arrays in Js
PDF
No ratings yet
Arrays in Js
6 pages
03 - JavaScript Arrays
PDF
No ratings yet
03 - JavaScript Arrays
15 pages
Projector
PDF
No ratings yet
Projector
15 pages
Type Script
PDF
No ratings yet
Type Script
11 pages
Chap 02 Array - Function - String
PDF
No ratings yet
Chap 02 Array - Function - String
75 pages
Javascript Important Method
PDF
No ratings yet
Javascript Important Method
14 pages
JavaScript Arrays
PDF
No ratings yet
JavaScript Arrays
13 pages
Js Notes
PDF
No ratings yet
Js Notes
12 pages
Angular-13 Full
PDF
No ratings yet
Angular-13 Full
279 pages
Arrays in JS 22
PDF
No ratings yet
Arrays in JS 22
8 pages
Unit-2 Array, Function and String
PDF
No ratings yet
Unit-2 Array, Function and String
60 pages
What Are Arrays in JavaScript
PDF
No ratings yet
What Are Arrays in JavaScript
9 pages
Type Script
PDF
No ratings yet
Type Script
37 pages
JSSSSSSSSSSSSSSSSSSSSSSS
PDF
No ratings yet
JSSSSSSSSSSSSSSSSSSSSSSS
1 page
A Comprehensive Guide To JavaScript Arrays - Part 1
PDF
No ratings yet
A Comprehensive Guide To JavaScript Arrays - Part 1
3 pages
1 Arrays
PDF
No ratings yet
1 Arrays
4 pages
App Settings Demystified (C# & VB)
PDF
No ratings yet
App Settings Demystified (C# & VB)
20 pages
JavaScript Arrays
PDF
No ratings yet
JavaScript Arrays
1 page
Comments: Javascript Provides Seven Different Data Types
PDF
No ratings yet
Comments: Javascript Provides Seven Different Data Types
28 pages
Intro To JavaScript Ojects
PDF
No ratings yet
Intro To JavaScript Ojects
85 pages
Mastering Javascript Arrays
PDF
No ratings yet
Mastering Javascript Arrays
25 pages