10 Dealing with collections
This chapter covers
- Using array functions
- Creating dictionaries with maps
- Managing unique values with sets
- How to preserve immutable collections
Now that we’ve spent some time wrangling the particularities of objects in JavaScript, we’ll move on to a closely related topic: collections. We’ll start with arrays, the most common type of collection in JavaScript. We’ll explore some of the built-in array methods that allow you to take advantage of functional programming paradigms.
Next we’ll meet two newer collection types: maps and sets. Maps are collections of key-value pairs with capabilities beyond those of ordinary objects. Sets are collections of items in which no item can appear more than once.
Lastly, we’ll discuss mutability and why it’s often desirable for objects and collections to be immutable. We’ll see how TypeScript can guard against mutations with read-only types. We’ll also meet a popular package, Immer, that provides a convenient way to work with immutable objects and collections.
Let’s begin our exploration with the simplest and most common of all collections: arrays.
10.1 Arrays
If your programming background is in a typed language such as C, you might think of arrays as sequential chunks of memory that house items of the same type, where each chunk of memory is of fixed size and has an associated index through which you can easily access it.