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
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:
(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:
Making new arrays
These leave the original alone and return a new array:
const copy = base; does not copy anything: both names point at the same array. Use [...base] for a real (shallow) copy.
Searching and joining
Visiting every item
Sorting - read this twice
sort() with no argument converts the items to strings and sorts alphabetically. For numbers that is wrong:
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:
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
sortandreversereturn a new array. They change the original, and return that same array. a === bon two arrays compares identity, not contents:[1] === [1]isfalse.- Using an index at or past
length; it givesundefined, and arithmetic on it givesNaN. const copy = original;and then being surprised that editingcopyeditsoriginal.
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.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…