Skip to content
Lesson 10 of 15

Step 1 of 7 · Reading · ~3 min

Learn

Collections

Arrays

An array is an ordered list of values. By the end of this lesson you can create arrays, read and change them, search them, and sort them correctly, including the one default that surprises almost everyone.

Creating and reading

javascript

An array can hold any values, including other arrays: [[1, 2], [3, 4]][1][0] is 3.

Reading a list from input

A line such as 3 8 2 arrives as one string. Split it on spaces to get an array of strings, then convert each one to a number:

javascript

(map is the next-but-one lesson; for now treat this line as the standard way to read numbers.) Without the conversion you would have strings, and "10" < "9" is true.

Changing an array in place

These methods mutate, that is, they modify the array they are called on:

javascript

Making new arrays

These leave the original alone and return a new array:

javascript

const copy = base; does not copy anything: both names point at the same array. Use [...base] for a real (shallow) copy.

Searching and joining

javascript

Visiting every item

javascript

Sorting - read this twice

sort() with no argument converts the items to strings and sorts alphabetically. For numbers that is wrong:

javascript

Pass a comparison function that takes two items and returns a negative number if the first belongs first, positive if the second does, zero if tied:

javascript

sort also changes the array it is called on. When the original order still matters, sort a copy: [...ages].sort(...).

Common mistakes

  • sort() on numbers without a comparison function: [10, 9, 1] becomes [1, 10, 9].
  • Assuming sort and reverse return a new array. They change the original, and return that same array.
  • a === b on two arrays compares identity, not contents: [1] === [1] is false.
  • Using an index at or past length; it gives undefined, and arithmetic on it gives NaN.
  • const copy = original; and then being surprised that editing copy edits original.

Your exercise

Sort a list of numbers and report its middle value. The starter reads the numbers into an array. Think about what changes between a list with an odd count and one with an even count.

Up nextObjectsCollections

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…