Cut and Copy Parts of an Array

At the end of the last lesson, your main.js held tonight’s queue—Codenames, Azul, and Ticket to Ride—plus the two search functions isQueued() and positionOf(). Jonas wants Azul out, but it sits in the middle, where shift() and pop() can’t reach.

In this lesson, you’ll learn the array methods that work anywhere in an array. You’ll take a game out by name, copy part of the queue without changing it, and draw a game at random so it can’t come up twice. For each call, you’ll check what it returns and what the array holds afterward. Start with Jonas’s veto.

Take a Game Out of the Middle

The end methods only reach the first and last items, so for a veto you need splice(), a method that takes a position. Its first argument is the index to start at, and its second is how many items to remove. Like push() and shift(), it changes the array you call it on.

Remove and Insert by Position

You found Azul at index 1 in the last lesson. Add two lines below the three you kept in main.js. If you’re starting here, set up the scratch page as in Add and Remove at the Ends, then put all five lines in main.js:

Language: JavaScript Filename: scratch/main.js
const queue = ["Codenames", "Azul", "Ticket to Ride"];
const isQueued = (name) => queue.includes(name);
const positionOf = (name) => queue.indexOf(name);
console.log("splice returned:", queue.splice(1, 1));
console.log("Queue:", queue);

Save, reload, and look at the Console:

Language: Program Output
splice returned: ['Azul']
Queue: (2) ['Codenames', 'Ticket to Ride']

The call changed queue itself, and Ticket to Ride moved down to index 1. It returned an array of the removed items, not the item on its own, because a single call can remove several items.

Wei and Amara suggest Carcassonne and Catan, and the guests want both right after Codenames. Any arguments after the count are items for splice() to insert at the start index. A count of 0 removes nothing. Add three lines:

Language: JavaScript Filename: scratch/main.js
const added = queue.splice(1, 0, "Carcassonne", "Catan");
console.log("splice returned:", added);
console.log("Queue:", queue);

Save and reload. The whole file runs again, so the new lines come last:

Language: Program Output
splice returned: ['Azul']
Queue: (2) ['Codenames', 'Ticket to Ride']
splice returned: []
Queue: (4) ['Codenames', 'Carcassonne', 'Catan', 'Ticket to Ride']

This time splice() returned an empty array, since it removed nothing. The two new games went in at index 1, in the order you passed them, and Ticket to Ride moved up to index 3.

Remove a Game by Name

Typing 1 worked because you’d looked the index up first. A guest asks for a game by name, though, so the scorekeeper needs a function that finds the index and removes the item in one step. You already have positionOf() to find it.

What should the function do when the game isn’t there? Then positionOf() returns -1, and splice() reads a negative start the way at() does, counting back from the end. So queue.splice(-1, 1) would remove the last game in the queue without any error. The function has to check for -1 before it calls splice(). Add it, with two vetoes of Catan, because Jonas and Sam both dislike it:

Language: JavaScript Filename: scratch/main.js
const removeGame = (name) => {
  const index = positionOf(name);
  if (index === -1) {
    return false;
  }
  queue.splice(index, 1);
  return true;
};
console.log("Catan removed?", removeGame("Catan"));
console.log("Catan removed again?", removeGame("Catan"));
console.log("Queue:", queue);

The three new lines come last:

Language: Program Output
splice returned: ['Azul']
Queue: (2) ['Codenames', 'Ticket to Ride']
splice returned: []
Queue: (4) ['Codenames', 'Carcassonne', 'Catan', 'Ticket to Ride']
Catan removed? true
Catan removed again? false
Queue: (3) ['Codenames', 'Carcassonne', 'Ticket to Ride']

The first call found Catan at index 2 and removed it. The second found nothing, so the function returned false from the if block before splice() ran, and Ticket to Ride is still in the queue. Because removeGame() returns true or false, the code that calls it can tell the guest whether the veto did anything.

If the negative start still feels odd, ask the mentor to walk you through it:

Copy Part of the Queue

Sometimes you need part of the queue without changing it. Sam has to leave early and wants to see the next two games. The slice() method copies a range into a new array and leaves the original unchanged.

To give slice() something to cut, replace your experiment with a longer queue, all five of Priya’s games:

Language: JavaScript Filename: scratch/main.js
const queue = [
  "Codenames", "Azul", "Catan",
  "Carcassonne", "Ticket to Ride",
];
console.log("Next two:", queue.slice(0, 2));
console.log("Last two:", queue.slice(-2));
console.log("Queue:", queue);

Save and reload:

Language: Program Output
Next two: (2) ['Codenames', 'Azul']
Last two: (2) ['Carcassonne', 'Ticket to Ride']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']

The call slice(0, 2) copied from index 0 up to but not including index 2, so the copy holds two games. A negative start counts back from the end, so slice(-2) copied the last two. With no end argument, slice() copies to the end of the array, and with no arguments at all, it copies the whole array. After both calls, queue still holds all five games.

Tell slice() and splice() Apart

The two names differ by one letter, and their second arguments mean different things. In slice(), it’s the index to stop before. In splice(), it’s how many items to remove. Add these lines, and before you save, predict for each call what it returns and what queue holds afterward:

Language: JavaScript Filename: scratch/main.js
console.log("slice returned:", queue.slice(1, 3));
console.log("Queue:", queue);
const removed = queue.splice(1, 3);
console.log("splice returned:", removed);
console.log("Queue:", queue);

Note your four answers, and then save and reload. The new lines come last:

Language: Program Output
Next two: (2) ['Codenames', 'Azul']
Last two: (2) ['Carcassonne', 'Ticket to Ride']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
slice returned: (2) ['Azul', 'Catan']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
splice returned: (3) ['Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']

With the same arguments, slice(1, 3) copied the two games at indices 1 and 2 and left the queue alone. The splice(1, 3) call removed three games from index 1 and returned them, leaving two in the queue. When a task says “show” or “copy,” use slice(). When it says “take out” or “put in,” use splice().

To see the pattern beyond one pair of arguments, move the two sliders below. Both calls start from the same five-game queue each time, and the table marks what slice() copies and what splice() removes:

Interactive diagram — enable JavaScript to view.

Whatever you pick, slice() leaves all five games in queue, while splice() takes out exactly what it returns. A negative first argument counts back from the end in both calls, and the second argument is still an index to stop before for slice() and a count for splice().

For more practice, the button below opens a conversation with the mentor. You’ll get calls one at a time. For each one, you reply with what it returns and what the array holds afterward, and then the mentor checks your answer:

Join and Reverse Arrays

You can put the three games in removed back into a list with concat(). It returns a new array with the items of the array you call it on, followed by the items of the arrays you pass. You might try push(removed) instead, but that adds the whole array as one item, so the queue would hold a game list inside it. Add three lines:

Language: JavaScript Filename: scratch/main.js
const restored = queue.concat(removed);
console.log("concat returned:", restored);
console.log("Queue:", queue);

The last two lines are new:

Language: Program Output
Next two: (2) ['Codenames', 'Azul']
Last two: (2) ['Carcassonne', 'Ticket to Ride']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
slice returned: (2) ['Azul', 'Catan']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
splice returned: (3) ['Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']
concat returned: (5) ['Codenames', 'Ticket to Ride', 'Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']

Like slice(), concat() built a new array, so queue kept its two games.

Wei suggests playing the games at the back of restored first. The reverse() method flips an array’s order. Add three more lines that log what reverse() returns and what restored holds afterward:

Language: JavaScript Filename: scratch/main.js
const reversed = restored.reverse();
console.log("reverse returned:", reversed);
console.log("Restored:", restored);

The two new lines show the same order:

Language: Program Output
Next two: (2) ['Codenames', 'Azul']
Last two: (2) ['Carcassonne', 'Ticket to Ride']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
slice returned: (2) ['Azul', 'Catan']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
splice returned: (3) ['Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']
concat returned: (5) ['Codenames', 'Ticket to Ride', 'Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']
reverse returned: (5) ['Carcassonne', 'Catan', 'Azul', 'Ticket to Ride', 'Codenames']
Restored: (5) ['Carcassonne', 'Catan', 'Azul', 'Ticket to Ride', 'Codenames']

Unlike concat(), reverse() changed restored in place, and it returned that same array, not a copy. That’s why reversed and restored show the same order. The two names lead to one array. That’s all you need to know about it for now, because the next lesson starts there.

To flip the order and keep the original, reverse a copy. Priya wants the queue back to front, so copy it with queue.slice() and reverse that. Add four lines:

Language: JavaScript Filename: scratch/main.js
const backToFront = queue.slice();
backToFront.reverse();
console.log("Back to front:", backToFront);
console.log("Queue:", queue);

The last two lines are new:

Language: Program Output
Next two: (2) ['Codenames', 'Azul']
Last two: (2) ['Carcassonne', 'Ticket to Ride']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
slice returned: (2) ['Azul', 'Catan']
Queue: (5) ['Codenames', 'Azul', 'Catan', 'Carcassonne', 'Ticket to Ride']
splice returned: (3) ['Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']
concat returned: (5) ['Codenames', 'Ticket to Ride', 'Azul', 'Catan', 'Carcassonne']
Queue: (2) ['Codenames', 'Ticket to Ride']
reverse returned: (5) ['Carcassonne', 'Catan', 'Azul', 'Ticket to Ride', 'Codenames']
Restored: (5) ['Carcassonne', 'Catan', 'Azul', 'Ticket to Ride', 'Codenames']
Back to front: (2) ['Ticket to Ride', 'Codenames']
Queue: (2) ['Codenames', 'Ticket to Ride']

The copy came out back to front, and queue still starts with Codenames. When a method changes its array in place, give it a copy from slice().

Draw a Game at Random

When the guests can’t agree, Priya draws the next game at random. A draw has to pick a valid index, and a game that’s been drawn mustn’t come up again.

The Math object helps with the first part. Math.random() returns a number from 0 up to but not including 1. Multiply it by queue.length, and you get a number from 0 up to the length. Math.floor() rounds that down to a whole number, so as long as the queue holds at least one game, the result is an index inside it.

For the second part, splice() removes the drawn game, so it can’t be picked twice. Replace your experiment with the full queue and a drawGame() function:

Language: JavaScript Filename: scratch/main.js
const queue = [
  "Codenames", "Azul", "Catan",
  "Carcassonne", "Ticket to Ride",
];
const drawGame = () => {
  if (queue.length === 0) {
    return null;
  }
  const index = Math.floor(Math.random() * queue.length);
  return queue.splice(index, 1)[0];
};
console.log("Drawn:", drawGame());
console.log("Drawn:", drawGame());
console.log("Queue:", queue);

Save and reload. Your results will probably differ from the output below, because the draw is random. One run showed this:

Language: Program Output
Drawn: Catan
Drawn: Carcassonne
Queue: (3) ['Codenames', 'Azul', 'Ticket to Ride']

Each draw removed its game, so the queue shrank to three, and neither drawn game can come up again. The [0] after splice(index, 1) takes the one game out of the returned array, so drawGame() returns a name, not an array. Because queue.length drops with every draw, the next index fits the shorter queue. Reload a few times to see different pairs.

On a sixth draw, once all five games are gone, queue.length is 0. Without the check at the top, the index would be 0, but there’d be no game there. The call to splice() would remove nothing, and drawGame() would return undefined.

The if check catches the empty queue first, so drawGame() returns null and the code that calls it can tell Priya that every game has been drawn.

If the arithmetic behind the index isn’t clear yet, the mentor can take it one step at a time:

You’ve seen that reverse() returned the very array it changed, so reversed and restored named one array. In Follow Two Names to One Array, you’ll see what happens when two names lead to the same array, and why a copy from slice() keeps the queue safe.

Become a Member to join the conversation.