Triple Clicked explainer


#1

The aim of this puzzle: Find the 3 copies of 'brush', and replace it with 'comb'.

Walkthrough of the solution: When you run the starter code, you can see the entire shoppingCart. If you look at the 3rd, 4th, and 5th items, they’re all 'brush'. You want to select that section and replace it with 'comb'. That’s a job for the .splice() method.

.splice() is attached to the array you want to modify, and it takes 3 arguments in its parentheses:

  1. The starting index of the selection
  2. How many items are in the selection
  3. The new item to be inserted in place of the selection

The starting index can be found by searching the array and using .indexOf(). Part of the code is completed for you: let index = shoppingCart. That will store the entire array in index, but it should really only store the index number of the first 'brush'. Attach .indexOf('brush') to the shoppingCart.

Now, you can use that index in a .splice() call. On a new line, between the let index = ... and the console.log(), add shoppingCart.splice(). The 1st argument should be the index. The next argument is the number of items to select, which is 3. Finally, you add the new item to insert, which should be the string 'comb'.

Your final command will be shoppingCart.splice(index, 3, 'comb').

Sample code solution:
(Tap below to reveal)

Since this is part of the final topic of the Arrays course and it is testing your knowledge, there is no sample solution code.

JavaScript Concepts: console.log(), import, .indexOf(), .splice()


#2