Dealing with collections

 

This chapter covers:

  • Creating and modifying arrays

  • Using and reusing array functions

  • Creating dictionaries with maps

  • Creating collections of unique objects with sets

Now that we’ve spent some time wrangling the particularities of object-orientation in JavaScript, we’ll move on to a closely related topic: collections of items. We’ll start with arrays, the most basic type of collection in JavaScript, and look at some array peculiarities you may not expect if your programming background is in another programming language. We’ll continue by exploring some of the built-in array methods that will help you write more elegant array-handling code.

Next, we’ll discuss two new ES6 collections: maps and sets. Using maps, you can create dictionaries of a sort that carry mappings between keys and values—a collection that’s extremely useful in certain programming tasks. Sets, on the other hand, are collections of unique items in which each item can’t occur more than once. Let’s begin our exploration with the simplest and most common of all collections: arrays.

Do you know?

Q1:

What are some of the common pitfalls of using objects as dictionaries or maps?

Q2:

What value types can a key/value pair have in a Map?

Q3:

Must the items in a Set be of the same type?

9.1. Arrays

9.1.1. Creating arrays

9.1.2. Adding and removing items at either end of an array

9.1.3. Adding and removing items at any array location

9.1.4. Common operations on arrays

9.1.5. Reusing built-in array functions

9.2. Maps

9.2.1. Don’t use objects as maps

9.2.2. Creating our first map

9.2.3. Iterating over maps

9.3. Sets

9.3.1. Creating our first set

9.3.2. Union of sets

9.3.3. Intersection of sets

9.3.4. Difference of sets

9.4. Summary

9.5. Exercises