Salesforce Certified JavaScript Developer I · Lesson 5

Manipulating Data with Arrays

Six rules decide almost every array question. Free to watch, with a free slide PDF and practice questions.

Chapters

  1. 0:00 Manipulating Data with Arrays
  2. 0:33 Quick recap: truthy, falsy, and defaults
  3. 1:18 Six rules decide almost every array question
  4. 2:05 One table holds the whole lesson
  5. 3:11 Some methods change the array in place
  6. 4:18 A copy is shallow: object elements are shared
  7. 5:16 Adding, removing, and copying elements
  8. 6:30 Know what each method returns
  9. 7:34 Iterating and searching
  10. 8:40 indexOf uses ===, but includes finds NaN
  11. 9:50 map, reduce, join, and split
  12. 11:03 Default sort compares text, not numbers
  13. 12:13 How default sort really works
  14. 13:00 Newer methods copy instead of mutating
  15. 14:15 flat goes one level; flatMap maps then flattens one
  16. 15:27 Sparse arrays: some methods skip empty slots
  17. 16:19 Six terms to say in your own words
  18. 16:58 Order totals without touching the source
  19. 18:04 Eight questions, closed book
  20. 19:13 A developer runs the following code. What is logged?
  21. 20:11 [ 'Banana', 'Strawberry' ] [ 'Apple', 'Mango' ]
  22. 21:20 Four array rules to keep
  23. 22:01 Now test it, then move to JSON

Test yourself on manipulating data with arrays

Practice questions for this lesson come with a full explanation of why each answer is right or wrong, and link back to the exact moment in the video.

Take the free diagnostic

Transcript

Read the full lesson text

Manipulating Data with Arrays 0:00

Welcome to module one, lesson five: manipulating data with arrays. This module is called Variables, Types, and Collections, and it carries twenty three percent of the exam. In this lesson we look at the everyday array methods: splice, sort, and reduce. Some of them change the original array, some return a new one, and the exam asks which is which. By the end, you will know which array methods change the original, what each one returns, and how to avoid the sort trap.

Quick recap: truthy, falsy, and defaults 0:33

Before we start, a quick recap from lesson four. First, eight values are falsy: false, zero, negative zero, big int zero, the empty string, null, undefined, and nan. Second, the lookalikes are truthy: the string zero, the string false, an empty array, and an empty object. Third, double pipe replaces any falsy value, while double question mark replaces only null and undefined. And fourth, double equals is not a truthiness test: null double equals zero is false. Today we move to lists of values: arrays. Which methods change the original, and what does each one return?

Six rules decide almost every array question 1:18

Here is what you will learn. Six rules decide almost every array question on the exam. This domain is twenty three percent of the exam. This lesson boils down to six rules, and nine array methods mutate, meaning they change the original array. The six rules are these. One, mutating or not. Two, what each method returns. Three, iterating and searching. Four, transforming with map and reduce. Five, the default sort is text order. And six, copying methods and flat. We will also cover shallow copies, join and split, and sparse arrays. Rules one, two, and five produce most of the questions, so we slow down there.

One table holds the whole lesson 2:05

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Mutate. The rule is that sort, reverse, and splice change the array. The trap is that sort returns the same array, not a copy. The safe habit is to copy first. Return. The rule is that push gives the new length, and splice gives the removed elements. The trap is that push does not return the array. The safe habit is to read the return value. Sort. The rule is that the default order compares text. The trap is that one, two, fifteen becomes one, fifteen, two. The safe habit is to pass a comparator. Reduce. The rule is that it folds the array down to one value. The trap is that an empty array without a start value throws. The safe habit is to always give a start value. One practical rule to carry with you: know what changes and what comes back, then copy before you mutate.

Some methods change the array in place 3:11

Rule one. Some array methods change the array in place, and the rest build a new one. Look at the code. The first group is mutating, which means the original changes. Pop, push, shift, and unshift work on the ends of the array. Splice, sort, and reverse change it too. And "copy within" and fill also mutate, which makes nine mutating methods in all. The second group is non mutating, so each one returns a new array. Slice, concat, map, and filter are the classic ones. The newer copies are "to reversed", "to sorted", and "to spliced". So pop, push, shift, unshift, splice, sort, and reverse change the original. Slice, concat, map, and filter return a new array. To avoid mutation, copy first, with arr dot slice, or by spreading the array into new square brackets. And remember, "copy within" and fill also mutate. The exam point: sort, reverse, and splice mutate; slice, concat, map, and filter do not.

A copy is shallow: object elements are shared 4:18

Here is a trap about copies. A copy of an array is shallow. The wrong shortcut says, a copy gives me independent objects. The correct exam test says, primitives are copied by value, but object elements stay shared references. Look at the code. We create orig, an array holding one object, with n equal to one. Then copy spreads orig into a new array. It is a different array, but its first element is the very same object. So when we set copy zero dot n to ninety nine, console dot log of orig zero dot n prints ninety nine too. For an independent copy, use "structured clone", as in the last line. Now deep is fully independent of orig. A json round trip, where you "stringify" and then "parse", also makes a deep copy. The practical rule: for a deep copy use "structured clone", or the json round trip.

Adding, removing, and copying elements 5:16

Now adding, removing, and copying elements. Splice, slice, and concat look alike, but they behave very differently. Look at the code. We start with fruits: Apple, Banana, Strawberry, and Mango. Then fruits dot splice of one, two removes two elements, starting at index one. Splice returns the removed elements, so removed holds Banana and Strawberry. And the original now holds only Apple and Mango. Next, slice. The array t, e, s, t, sliced from one to three, gives e and s, because the end index is exclusive. Then concat. One, two, concat the array three, four, and the plain value five, gives one through five. In short, splice takes a start, a delete count, and then any items. It deletes, inserts, or replaces, all in place. Slice takes a start and an end, and returns a new array. Negative indexes count from the end. And concat spreads array arguments, but adds other values as they are. The exam point: splice returns the removed elements as an array.

Know what each method returns 6:30

Now a trap that catches many people: know what each method returns, not only what it does. The wrong shortcut says, push returns the array, and sort returns a copy. The correct exam test says, push and unshift return the new length, and sort and reverse return the same array. Here is the table. Push and unshift return the new length. Pop and shift return the removed element. Splice returns an array of the removed elements. And sort and reverse return the same array, already changed. Look at the code. We declare a as one, two. Then console dot log of a dot push of three, a dot unshift of zero, and a. Push adds three at the end, so it returns three, the new length. Unshift adds zero at the front, so it returns four. And a is now zero, one, two, three. So never expect an array back from push. Read the return value, not only the side effect.

Iterating and searching 7:34

Next, iterating and searching. Pick the method by the shape of the answer you need. Look at the code. Users is an array of three objects, with ids one, two, and three. Users dot find with id equal to one returns the first matching object, John. Users dot filter with id less than three returns an array of two users. Now with id greater than five: find returns undefined, but filter returns an empty array. Every callback receives the element, the index, and the array. And "for each" returns undefined, so it is for side effects, not for building a result. Find gives one element, or undefined. And "find index" gives an index, or minus one when nothing matches. Filter always gives an array, even when it is empty. Some is true if any element passes, and every is true only if all of them pass. Both stop early, as soon as the answer is known. The exam point: find returns one element or undefined; filter always returns an array.

Now a trap about searching. "Index of" uses triple equals, but includes can find nan. Look at the code. In the first line, the array one, zero, false, "index of" false, returns two. Strict equality converts nothing, so zero is skipped. In the second line, an array holding nan, "index of" nan, returns minus one. Nan is not equal to itself, so strict equality never matches it. In the third line, the same array with includes of nan returns true. Includes treats nan as equal to itself. One more check. "Type of" an empty array is the string object. Array dot "is array" of an empty array is true, and that is the right test. So "index of" uses strict equality and gives an index, or minus one. Includes gives a boolean, and it finds nan. Nan triple equals nan is false, which is why "index of" misses it. And Array dot "is array" detects arrays, because "type of" says object. The exam point: includes finds nan, but "index of" does not.

map, reduce, join, and split 9:50

Rule four: transforming with map and reduce, plus join and split. Look at the code. Names holds Bilbo and Gandalf. Names dot map, with the length of each string, returns a new array: five and seven. Names dot join with a semicolon returns one string, Bilbo semicolon Gandalf. And the string a semicolon b, split on a semicolon, gives an array: a and b. Now reduce. Nums holds one through five. Nums dot reduce, with sum plus n, starting at zero, returns fifteen. The accumulator carries the running total from call to call. But reduce on an empty array, with no start value, throws a Type Error. So map returns a new array of the same length. Reduce takes a callback and an initial value, and collapses the array to one value. Reducing an empty array with no initial value throws. Join makes a string, and split makes an array. The practical rule: always pass an initial value to reduce. Map transforms, filter selects, find returns the first match, and reduce collapses.

Default sort compares text, not numbers 11:03

Rule five, and the biggest trap in this lesson: the default sort compares text, not numbers. The wrong shortcut says, sort puts numbers in numeric order. The correct exam test says, the default sort converts elements to strings, so you must pass a comparator for numbers. Look at the code. Sorting one, two, fifteen with no argument gives one, fifteen, two. The strings are compared character by character, so the string fifteen lands before the string two. Pass a comparator, a and b, arrow, a minus b, and you get one, two, fifteen. A negative result puts a first, and a positive result puts b first. Here is a bigger example. The array is one, thirty, four, twenty one, and one hundred thousand. Calling sort with no argument gives one, one hundred thousand, twenty one, thirty, four. Read it as text: one, then one followed by zeros, then two, three, four. The exam point: without a comparator, one, two, fifteen sorted is one, fifteen, two.

How default sort really works 12:13

Here is how the default sort really works, in four facts. One. It sorts ascending, and the order is built on U T F sixteen code units of the string forms of the elements. That is why the character one comes before two. Two. Every undefined element goes to the end. Three. It sorts in place, and returns a reference to the same array. Sort makes no copy. Four. Empty slots stay empty, and they move to the end, after the undefined values. Because sort returns the same array, assigning the result does not protect the original. It just gives you two names for one array. The exam point: sort makes no copy. The array you sort is the array you get back.

Newer methods copy instead of mutating 13:00

Now the newer methods that copy instead of mutating. Look at the code. Values holds one, ten, twenty one, and two. Values dot "to sorted", with a minus b, returns one, two, ten, twenty one. And values is still one, ten, twenty one, two. Next, months holds Jan, Mar, Apr, and May. Months dot "to spliced" of one, zero, Feb, inserts Feb at index one, and returns the new array: Jan, Feb, Mar, Apr, May. Last, arr holds one through five. Arr dot with of two, six replaces index two in a copy. And arr dot with of minus one, zero replaces the last element. So "to sorted" is the copying version of sort. Note that "to spliced" returns the new array, not the removed items. With takes an index and a value, and replaces that one index in a copy. With throws a Range Error when the index is out of range. And "to spliced" never produces a sparse array; empty slots become undefined. The exam point: "to sorted", "to spliced", and with return new arrays; sort and splice change the original.

flat goes one level; flatMap maps then flattens one 14:15

Next, flat and "flat map". Both flatten nested arrays, but only by the depth you give them. Look at the code. Take zero, one, and then a nested array. Calling flat with no argument goes one level deep. So two comes out, but three, four, and five stay nested. The result is zero, one, two, and then the array three, four, five. Calling flat with Infinity flattens everything, giving zero through five in one flat array. Now "flat map". Take one, two, three, four, and map each x to an array holding an array of x times two. Map alone would wrap each result two levels deep. "Flat map" removes exactly one level, so each number stays wrapped in one array. So flat takes a depth, and it defaults to one. Full flattening needs Infinity as the depth. And "flat map" is map, then flat of depth one. Flat also removes empty slots from sparse arrays. The exam point: flat flattens one level by default, and "flat map" flattens exactly one level. Both return a new array and leave the original unchanged.

Sparse arrays: some methods skip empty slots 15:27

One more detail: sparse arrays. A sparse array has empty slots, which are not the same as undefined values. Some methods skip the empty slots. "For each", map, filter, reduce, some, and every all skip holes. Other methods treat empty slots as undefined. Find, "find index", includes, and join all see them as undefined. Look at the code. A is one, an empty slot, then three: you write two commas in a row. A dot "for each" logs one, then three, because the hole is skipped. But a dot includes of undefined is true, because includes sees the hole as undefined. Remember that sort moves empty slots to the end, and flat removes them. The exam point: the first group skips holes; the second group sees them as undefined.

Six terms to say in your own words 16:19

Six key terms to say in your own words. A mutating method changes the original array in place. A copying method returns a new array and leaves the original unchanged. A shallow copy is a new array whose object elements still reference the originals. A comparator is a function of a and b, passed to sort, that defines the order. A callback is a function of element, index, and array, passed to iterative methods. And an accumulator is the running value carried between reduce calls. Pause the video now. Cover each card and explain the term aloud.

Order totals without touching the source 16:58

Now the proof stage, starting with a lab: order totals without touching the source. Look at the code. Orders holds three orders: price five and quantity two, price seven and quantity one, and price four and quantity three. Totals maps each order to price times quantity. Sum reduces the totals with a start of zero. And sorted is totals "to sorted", largest first. Predict the totals, the sum, and the sorted copy on paper first, then run it in Node. Take two minutes on your own, and write your predictions down before checking. Now the answers. Totals is ten, seven, twelve. Sum is twenty nine. Sorted is twelve, ten, seven. And totals is still ten, seven, twelve, because "to sorted" made a copy. To verify, check that totals is not orders, that orders dot length is still three, and that Object dot "is" of sorted and totals is false, so they are different arrays. If any prediction was wrong, go back to the slide that explains it.

Eight questions, closed book 18:04

Self check: eight questions, closed book. Answer out loud, then I will reveal each one. One. What does the array one, two, dot push of three, return? Three, the new length. Two. What is one, two, fifteen sorted with no comparator? One, fifteen, two. Three. What does one, two, three, dot splice of one, one, return? An array holding two. Four. What is the "index of" nan in an array holding nan? Minus one. Five. What does reduce on an empty array, with no start value, do? It throws a Type Error. Six. What is one, then the array two and the array three, flattened once? One, two, and the array three. Seven. What does find return when nothing matches? Undefined. And eight. What does one, two, three, dot with of three, zero do? It throws a Range Error, because index three is out of range. How many did you get? Anything you missed, go back to its slide.

A developer runs the following code. What is logged? 19:13

Time for a practice question, taken from the question bank. This one is about the splice method. Pause the video and trace the code before you read the options. A developer runs the following code. What is logged? F is an array: Apple, Banana, Strawberry, Mango. R is f dot splice of one, two. Then console dot log of r, comma, f. Option A: the array Apple, Mango, then the array Banana, Strawberry. Option B: two, then the array Apple, Mango. Option C: the array Banana, Strawberry, then the array Apple, Banana, Strawberry, Mango. Option D: the array Banana, Strawberry, then the array Apple, Mango. Decide what splice removes, what it returns, and what is left. Pause now, and I will give you the answer on the next slide.

[ 'Banana', 'Strawberry' ] [ 'Apple', 'Mango' ] 20:11

The answer is D. The array Banana, Strawberry, then the array Apple, Mango. Here is why. Splice of one, two starts at index one and removes two elements, Banana and Strawberry. Splice returns those removed elements, so r holds Banana and Strawberry. And splice mutates the original, so f is left holding only Apple and Mango. Console dot log of r and f prints exactly that. Now the wrong options. A says Apple, Mango, then Banana, Strawberry. That swaps the two results: splice returns the removed items, and the array keeps the rest. B says two, then Apple, Mango. That thinks splice returns a count, but splice returns an array of the removed elements. C says Banana, Strawberry, then all four fruits. That forgets that splice mutates, so the original no longer holds all four. Every wrong option is a real misreading of splice. The takeaway: splice changes the original and returns the removed elements.

Four array rules to keep 21:20

Let's consolidate. Four array rules to keep. Mutate: sort, reverse, and splice change the original; slice, concat, map, and filter do not. Return: push gives the new length, splice gives the removed elements, and sort returns the same array. Sort: the default order is text, so pass a comparator, a minus b, for numbers. Copy: copies are shallow, and "to sorted", "to spliced", and with leave the original alone. Remember: know what changes, know what comes back, and copy before you mutate. If you can say these four cards from memory, you've got the lesson.

Now test it, then move to JSON 22:01

That completes lesson five. Now test it, then move on to json. The flow is: read it, predict it, test it. Read it means mutation, returns, and sort. Predict it means applying the rule. And your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Operating on json, we turn data into json text and back, and see what "stringify" drops. See you there.